const appCacheKey = import.meta.env.VITE_APP_NAME + 'STORE'

let cache = {}

const storage = {
  setItem(key, value) {
    if (cache[key] === value) return
    cache[key] = value

    // 这里后面看是否需要延迟写入
    localStorage.setItem(appCacheKey, JSON.stringify(cache))
  },
  getItem(key) {
    let value = cache[key]
    if (!key || isNull(value) || isUndefined(value)) {
      return null
    }

    return value
  },
  // 初始化 cache
  init() {
    const s = localStorage.getItem(appCacheKey)
    try {
      cache = JSON.parse(s)
    } catch (e) {
      console.warn(`${appCacheKey} init failed, it will be {}`)
    }
    if (isNull(cache) || isUndefined(cache)) cache = {}
  },
}

function isNull(v) {
  return v === null
}

function isUndefined(v) {
  return typeof v === 'undefined'
}

storage.init()

export default storage
