import mitt from 'mitt'
import { App } from 'vue'

const eventBus = mitt()

export interface Options {
  global: boolean
  inject: boolean
  globalPropertyName: string
  injectName: string
}
const defaultOptions: Options = {
  global: true,
  inject: true,
  globalPropertyName: '$eventBus',
  injectName: '$eventBus',
}

function install(app: App, options: Partial<Options>) {
  const opt = {
    ...defaultOptions,
    ...options,
  }
  if (opt.global) {
    app.config.globalProperties[opt.globalPropertyName] = eventBus
  }
  if (opt.inject) {
    app.provide(opt.injectName, eventBus)
  }
  return eventBus
}

type EventBus = { install: typeof install } & typeof eventBus
;(eventBus as EventBus).install = install

export default eventBus as EventBus
