import PubSub from 'pubsub-js'

function on(name, fn) {
  return PubSub.subscribe(name, (msg, envelope) => {
    fn(...envelope)
  })
}

function off(token) {
  return PubSub.unsubscribe(token)
}

function emit(name, ...data) {
  const event = {
    name,
    preventDefault: function() {
      event.defaultPrevented = true
    },
    waitUntil(p) {
      this.wait = p.then((data) => {
        // 把promise返回的值通过evt返回
        event.resolvedValue = data
        return event
      })
    },
    defaultPrevented: false,
  }
  event.wait = Promise.resolve(event)
  PubSub.publishSync(name, [event, ...data])
  return event.wait
}

function once(name, fn) {
  return PubSub.subscribeOnce(name, (msg, envelope) => {
    fn(...envelope)
  })
}
const eventBus = {
  on,
  off,
  emit,
  once,
}
export default eventBus
