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

const key = Keys.NOTIFICATION_LIMIT
const initialValue = Number(localStorage.getItem(key) || '10')
export const limitReactiveVar = makeVar<number>(initialValue)

export const useNotificationLimit = () => useReactiveVar(limitReactiveVar)

function change(value: number) {
  localStorage.setItem(key, value.toString())
}

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

window.addEventListener(
  'storage',
  ({ key: keystorage, newValue, oldValue }) => {
    if (keystorage === key) {
      if (newValue !== oldValue && newValue !== null) {
        limitReactiveVar(Number(newValue))
      }
    }
  }
)
