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()) {
      resolve(true)
    }
    const ch = new BroadcastChannel('focus')
    ch.onmessage = e => {
      if (e.data === 'hasFocus') {
        resolve(true)
      }
    }
    ch.postMessage('isFocused')
    setTimeout(() => {
      resolve(false)
    }, 500)
  })

export const callSystemNotification = async (
  ...params: ConstructorParameters<typeof Notification>
) => {
  if (!(await checkIfAnyTabsFocused()) && systemNotifications()) {
    const n = new Notification(...params)
    return n
  }
}
