/*

  Copyright (C) 2020 willipink.eu
  Author Moritz Münch moritzmuench@mailbox.org

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program. If not, see <http://www.gnu.org/licenses/>. */


/* manage cookies */
class Cookie {

  constructor(cookie_name='', value='', expire_days=365, path='/') {
    // create a new cookie if cookie_name and value are set

    if (cookie_name !== '' && value !== '') {
      this.set(cookie_name, value, expire_days, path)
    }
  }


  /* save a cookie */
  set(name, value, expire_days=365, path='/') {

    let date = new Date();
    date.setTime(date.getTime() + (expire_days * 24 * 60 * 60 * 1000));
    let expires = date.toUTCString();
    document.cookie = name + '=' + value + '; Expires=' + expires + '; Path=' + path + '; SameSite=Strict';
  }


  /* return a cookie */
  get(cookie_name) {

    let name = cookie_name + '=';
    let cookies = document.cookie.split(';');

    for (let i = 0; i < cookies.length; i++) {
      let cookie = cookies[i];

      while (cookie.charAt(0) == ' ') {
        cookie = cookie.substring(1);
      }

      if (cookie.indexOf(name) == 0) {
        return cookie.substring(name.length, cookie.length);
      }
    }

    return ''
  }


  /* delete a cookie */
  delete(name) {
    this.set(name, '', -1)
  }
}

export { Cookie };
