const Cookies = {
  cookieDataKey: "__cookies__",

  set(name, value, { expires, domain, path, secure, httpOnly } = {}) {
    let cookies = this._getCookieData();
    let expiresFormatted = "";

    if (expires instanceof Date) {
      expiresFormatted = expires.toUTCString();
    } else if (typeof expires === "number") {
      let expiresTime = new Date();
      expiresTime.setTime(expires * 1000);
      expiresFormatted = expiresTime.toUTCString();
    }

    cookies[name] = {
      value,
      expires: expiresFormatted,
      domain,
      path,
      secure,
      httpOnly
    };

    this._setCookieData(cookies);
  },

  get(name) {
    let cookies = this._getCookieData();

    // eslint-disable-next-line no-prototype-builtins
    if (cookies.hasOwnProperty(name)) {
      let { value, expires } = cookies[name];

      if (expires !== "" && new Date() > new Date(expires)) {
        delete cookies[name];
        this._setCookieData(cookies);
        return undefined;
      }

      return value;
    }

    return undefined;
  },

  getAll() {
    return this._getCookieData();
  },

  remove(name) {
    let cookies = this._getCookieData();

    // eslint-disable-next-line no-prototype-builtins
    if (cookies.hasOwnProperty(name)) {
      delete cookies[name];
      this._setCookieData(cookies);
    }
  },

  _getCookieData() {
    let cookies = uni.getStorageSync(this.cookieDataKey);
    return cookies ? JSON.parse(cookies) : {};
  },

  _setCookieData(cookies) {
    uni.setStorageSync(this.cookieDataKey, JSON.stringify(cookies));
  }
};

export default Cookies;
