import Keys from '@inject/shared/localstorage/keys'
import { makeVar, useReactiveVar } from '@inject/shared/utils/reactive'

const initialSettings: string = localStorage.getItem(Keys.SESSION_ID) || ''

export const sessionid = makeVar<string>(initialSettings)
export const useSessionid = () => useReactiveVar(sessionid)

function change(value: string) {
  localStorage.setItem(Keys.SESSION_ID, value)
}

window.addEventListener('storage', ({ key, newValue, oldValue }) => {
  if (key === Keys.SESSION_ID && newValue !== oldValue) {
    const parsedValue = JSON.parse(newValue || '')
    sessionid(parsedValue)
  }
})

sessionid.onNextChange(function onNext() {
  change(sessionid())
  sessionid.onNextChange(onNext)
})
