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

const initialSettings: boolean =
  localStorage.getItem(Keys.RELATIVE_TIME) === 'true'

export const relativeTime = makeVar<boolean>(initialSettings)
export const useRelativeTime = () => useReactiveVar(relativeTime)

function change(value: boolean) {
  localStorage.setItem(Keys.RELATIVE_TIME, value.toString())
}

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

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