import dayjs from 'dayjs'
import NotificationWorker from 'worker-loader!../workers/notification.js'
import { createRandom } from '@/helpers/uuidv4'

const clickEvents = {}
const showEvents = {}
const errorEvents = {}
const closeEvents = {}

const noop = () => {}

export const notificationWorker = new NotificationWorker()

const notificationClicked = data => {
  const activeFn = clickEvents[data.callback_key]
  if (typeof activeFn === 'function') {
    activeFn(data)
  }
  delete clickEvents[data.callback_key]
}

const notificationShowed = data => {
  const activeFn = showEvents[data.callback_key]
  if (typeof activeFn === 'function') {
    activeFn(data)
  }
  delete showEvents[data.callback_key]
}

const notificationErrored = data => {
  const activeFn = errorEvents[data.callback_key]
  if (typeof activeFn === 'function') {
    activeFn(data)
  }
  delete errorEvents[data.callback_key]
}

const notificationClosed = data => {
  const activeFn = closeEvents[data.callback_key]
  if (typeof activeFn === 'function') {
    activeFn(data)
  }
  delete closeEvents[data.callback_key]
}

notificationWorker.addEventListener('message', evt => {
  if (evt.data.type === 'NotificationClicked') {
    notificationClicked(evt.data.data || {})
  } else if (evt.data.type === 'NotificationShowed') {
    notificationShowed(evt.data.data || {})
  } else if (evt.data.type === 'NotificationErrored') {
    notificationErrored(evt.data.data || {})
  } else if (evt.data.type === 'NotificationClosed') {
    notificationClosed(evt.data.data || {})
  }
})

export const createNotification = data => {
  /**
   *
   * @param { Object } 会原样在onClick返回
   *
   */

  const { onClick = noop, onShow = noop, onError = noop, onClose = noop, ...rest } = data
  const timemap = dayjs().valueOf()
  const callback_key = `${timemap}_${createRandom()}`
  clickEvents[callback_key] = onClick
  showEvents[callback_key] = onShow
  errorEvents[callback_key] = onError
  closeEvents[callback_key] = onClose
  notificationWorker.postMessage({
    ...rest,
    timemap,
    callback_key,
    type: 'create'
  })
}
