import { validateNull } from './validate'

const keyName = 'platform_'
const expireTimeMs = 24 * 60 * 60 * 1000

interface StoreObject {
  dataType: string
  content: any
  datetime: number
}

export const setStore = (name: string, content: any, sessionFlag = false): void => {
  const obj: StoreObject = {
    dataType: typeof content,
    content,
    datetime: new Date().getTime()
  }
  const key = keyName + name
  const value = JSON.stringify(obj)
  if (sessionFlag) {
    window.sessionStorage.setItem(key, value)
  } else {
    window.localStorage.setItem(key, value)
  }
}

export const getStore = (name: string, sessionFlag = false): any => {
  const storage = sessionFlag ? window.sessionStorage : window.localStorage
  const raw = storage.getItem(keyName + name)
  if (validateNull(raw)) return undefined
  let obj: StoreObject
  try {
    obj = JSON.parse(raw!)
  } catch {
    return raw
  }
  if (obj.dataType === 'string') return obj.content
  if (obj.dataType === 'number') return Number(obj.content)
  if (obj.dataType === 'object') return obj.content
  return obj.content
}

export const isExpired = (name: string, sessionFlag = false): boolean => {
  const storage = sessionFlag ? window.sessionStorage : window.localStorage
  const raw = storage.getItem(keyName + name)
  if (validateNull(raw)) return true
  let obj: StoreObject
  try {
    obj = JSON.parse(raw!)
  } catch {
    return true
  }
  return new Date().getTime() - obj.datetime > expireTimeMs
}

export const removeStore = (name: string): void => {
  window.localStorage.removeItem(keyName + name)
  window.sessionStorage.removeItem(keyName + name)
}

export const clearStore = (): void => {
  window.localStorage.clear()
  window.sessionStorage.clear()
}
