class LocalStorageCacheCell {
  constructor (data, timeout) {
    // 缓存的数据
    this.data = data
    // 设置超时时间,单位秒
    this.timeout = timeout
    // 对象创建时候的时间
    this.createTime = Date.now()
  }
}

let instance = null
let timeoutDefault = 1200

function isTimeout (name) {
  const data = JSON.parse(localStorage.getItem(name))
  if (!data) return true
  if (data.timeout === 0) return false
  const currentTime = Date.now()
  const overTime = (currentTime - data.createTime) / 1000
  if (overTime > data.timeout) {
    localStorage.removeItem(name)
    return true
  }
  return false
}

class LocalStorageCache {
  // 将数据存储在本地缓存中指定的 name 中
  // timeout设置为0表示永久缓存
  set (name, data, timeout = timeoutDefault) {
    const cachecell = new LocalStorageCacheCell(data, timeout)
    return localStorage.setItem(name, JSON.stringify(cachecell))
  }
  // 从本地缓存中获取指定 name 对应的内容
  get (name) {
    return isTimeout(name) ? null : JSON.parse(localStorage.getItem(name)).data
  }
  // 从本地缓存中移除指定 name
  delete (name) {
    return localStorage.removeItem(name)
  }
  // 返回一个布尔值,表示 name 是否在本地缓存之中
  has (name) {
    return !isTimeout(name)
  }
  // 清空本地数据缓存
  clear () {
    return localStorage.clear()
  }
  // 设置缓存默认时间
  setTimeoutDefault (num) {
    if (timeoutDefault === 1200) {
      return timeoutDefault = num
    }
    throw Error('缓存器只能设置一次默认过期时间')
  }
}

class ProxyLocalStorageCache {
  constructor () {
    return instance || (instance = new LocalStorageCache())
  }
}

export default ProxyLocalStorageCache