import { systemNotifications } from '../var/systemnotifications'

const channel = new BroadcastChannel('focus')
channel.onmessage = e => {
  if (e.data === 'isFocused') {
    if (document.hasFocus()) {
      channel.postMessage('hasFocus')
    }
  }
}

const checkIfAnyTabsFocused = () =>
  new Promise(resolve => {
    if (document.hasFocus()) {
      console.log('current tab has focus')
      resolve(true)
    }
    const ch = new BroadcastChannel('focus')
    console.log('setting up channel')
    ch.onmessage = e => {
      if (e.data === 'hasFocus') {
        console.log('some other tab has focus')
        resolve(true)
      }
    }
    ch.postMessage('isFocused')
    setTimeout(() => {
      console.log('no response, so no focus')
      resolve(false)
    }, 500)
  })

export const callSystemNotification = async (
  ...params: ConstructorParameters<typeof Notification>
) => {
  console.log('got request for notifications')
  if (!(await checkIfAnyTabsFocused()) && systemNotifications()) {
    console.log('permissions ok, we shall send')
    const n = new Notification(...params)
    return n
  }
}
