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

const initialValue: boolean =
  Notification.permission === 'granted' &&
  JSON.parse(localStorage.getItem(Keys.SYSTEM_NOTIFICATIONS) || 'false')
const systemNotificationsVar = makeVar<typeof initialValue>(initialValue)

export const systemNotifications = systemNotificationsVar
export const useSystemNotifications = () =>
  useReactiveVar(systemNotificationsVar)

function change(value: boolean) {
  const reValue = Notification.permission === 'granted' && value
  localStorage.setItem(Keys.SYSTEM_NOTIFICATIONS, reValue.toString())
}

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

window.addEventListener(
  'storage',
  ({ key: keystorage, newValue, oldValue }) => {
    if (keystorage === Keys.SYSTEM_NOTIFICATIONS) {
      if (newValue !== oldValue && newValue !== null) {
        systemNotificationsVar(JSON.parse(newValue))
      }
    }
  }
)
