import json from "superjson"

// https://gist.github.com/paulirish/5558557
export const hasLocalStorage = (() => {
  const mod = "TEST_LOCAL_STORAGE"
  try {
    localStorage.setItem(mod, mod)
    localStorage.removeItem(mod)
    return true
  } catch (e) {
    return false
  }
})()

export default {
  *keys() {
    for (let i = 0; i < localStorage.length; i++) {
      yield localStorage.key(i)
    }
  },

  setItem(key: string, value: any) {
    localStorage.setItem(key, json.stringify(value))
  },

  getItem(key: string) {
    const item = localStorage.getItem(key)
    if (item != null) {
      return json.parse(item)
    }
  },
}

if (process.env.NODE_ENV === "development" && hasLocalStorage) {
  Object.defineProperties(globalThis, {
    storage: {
      get() {
        return Object.fromEntries(
          Object.entries(localStorage).map(([key, rawValue]) => {
            let value
            if (rawValue.startsWith('{"json":')) {
              value = json.parse(rawValue)
            } else {
              try {
                value = JSON.parse(rawValue)
              } catch {
                value = rawValue
              }
            }
            return [key, value]
          }),
        )
      },
    },
  })
}
