// 默认缓存期限为7天
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7

const getKey = (key) => `${key}`.toUpperCase()
/**
 * cookie类
 * @class Cookie
 */
class Cookie {
  /**
   * 设置cookie
   * @param {string} name cookie 名称
   * @param {*} value cookie 值
   * @param {number=} expire 过期时间
   * 如果过期时间为设置，默认关闭浏览器自动删除
   * @example
   */
  set(name, value, expire = DEFAULT_CACHE_TIME) {
    document.cookie = `${getKey(name)}=${value}; Max-Age=${expire}`
  }

  /**
   * 根据名字获取cookie值
   * @param {String} name
   * @return {String}
   */
  get(name) {
    const cookieArr = document.cookie.split('; ')
    for (let i = 0, length = cookieArr.length; i < length; i++) {
      const kv = cookieArr[i].split('=')
      if (kv[0] === getKey(name)) {
        return kv[1]
      }
    }
    return ''
  }

  /**
   * 根据名字删除指定的cookie
   * @param {string} key
   */
  remove(key) {
    this.set(key, 1, -1)
  }

  /**
   * 清空cookie，使所有cookie失效
   */
  clear() {
    const keys = document.cookie.match(/[^ =;]+(?==)/g)
    if (keys) {
      for (let i = keys.length; i--; ) {
        document.cookie = keys[i] + '=0;expire=' + new Date(0).toUTCString()
      }
    }
  }
}

export const cookie = new Cookie()
