let Cache: any = {}
let SessionCache: any = {}

function _getStore(key: string, isSession?: boolean) {
  try {
    const storeType = isSession ? 'sessionStorage' : 'localStorage'
    return JSON.parse(window[storeType].getItem(key) as string)
  } catch (e) {}
}

function _setStore(key: string, value: any, isSession?: boolean) {
  try {
    const storeType = isSession ? 'sessionStorage' : 'localStorage'
    window[storeType].setItem(key, JSON.stringify(value))
  } catch (e) {}
}

function _removeStore(key: string, isSession?: boolean) {
  try {
    const storeType = isSession ? 'sessionStorage' : 'localStorage'
    window[storeType].removeItem(key)
  } catch (e) {}
}

function _clearStore(isSession?: boolean) {
  try {
    const storeType = isSession ? 'sessionStorage' : 'localStorage'
    window[storeType].clear()
  } catch (e) {}
}

export function getStore(key: string) {
  return Cache[key] !== undefined ? Cache[key] : (Cache[key] = _getStore(key))
}

export function setStore(key: string, value: any) {
  if (Cache[key] === value) return
  _setStore(key, value)
  Cache[key] = value
}

export function removeStore(key: string) {
  _removeStore(key)
  delete Cache[key]
}

export function clearStore() {
  _clearStore()
  Cache = {}
}

export function getSessionStore(key: string) {
  return SessionCache[key] !== undefined
    ? SessionCache[key]
    : (SessionCache[key] = _getStore(key, true))
}

export function setSessionStore(key: string, value: any) {
  if (SessionCache[key] === value) return
  _setStore(key, value, true)
  SessionCache[key] = value
}

export function removeSessionStore(key: string) {
  _removeStore(key, true)
  delete SessionCache[key]
}

export function clearSessionStore() {
  _clearStore(true)
  SessionCache = {}
}

export default {
  getStore,
  setStore,
  removeStore,
  clearStore,
  getSessionStore,
  setSessionStore,
  removeSessionStore,
  clearSessionStore
}
