export default {
  eventMap: new Map<string, Array<(val?: unknown) => void>>(),
  on(eventType: string, cb: (val?: unknown) => void) {
    const cbs = this.eventMap.get(eventType)
    if (cbs) {
      cbs.push(cb)
    } else {
      this.eventMap.set(eventType, [cb])
    }
  },
  once(eventType: string, cb: (val?: unknown) => void) {
    this.eventMap.set(eventType, [cb])
  },
  off(eventType: string, fn?: (val?: unknown) => void) {
    if (!this.eventMap.has(eventType)) return
    if (fn) {
      const cbs = this.eventMap.get(eventType)!
      const rIndex = cbs.findIndex((v) => v === fn)
      if (rIndex > -1) cbs.splice(rIndex, 1)
      this.eventMap.set(eventType, cbs)
    } else {
      this.eventMap.delete(eventType)
    }
  },
  offAll() {
    this.eventMap = new Map()
  },
  emit(eventType: string, val?: unknown) {
    const cbs = this.eventMap.get(eventType)
    if (cbs) cbs.forEach((cb) => cb(val))
  },
}

export const EVENT_KEY = {
  ENTER_FULLSCREEN: 'ENTER_FULLSCREEN',
  EXIT_FULLSCREEN: 'EXIT_FULLSCREEN',
  OPEN_COMMENTS: 'OPEN_COMMENTS',
  CLOSE_COMMENTS: 'CLOSE_COMMENTS',
  SHOW_SHARE: 'SHOW_SHARE',
  NAV: 'NAV',
  GO_USERINFO: 'GO_USERINFO',
  CURRENT_ITEM: 'CURRENT_ITEM',
  TOGGLE_CURRENT_VIDEO: 'TOGGLE_CURRENT_VIDEO',
  SINGLE_CLICK: 'SINGLE_CLICK',
  SINGLE_CLICK_BROADCAST: 'SINGLE_CLICK_BROADCAST',
  ITEM_TOGGLE: 'ITEM_TOGGLE',
  ITEM_PLAY: 'ITEM_PLAY',
  ITEM_STOP: 'ITEM_STOP',
  UPDATE_ITEM: 'UPDATE_ITEM',
  REMOVE_MUTED: 'REMOVE_MUTED',
  DIALOG_MOVE: 'DIALOG_MOVE',
  DIALOG_END: 'DIALOG_END',
}
