import { PluginFunction, VueConstructor } from 'vue'
import { directive } from './directive'

export let _Vue: VueConstructor

let installed = false

export const install: PluginFunction<undefined> = (Vue: VueConstructor) => {
  if (installed && _Vue === Vue) return
  installed = true

  _Vue = Vue

  const isDef = (v: unknown) => v !== undefined

  Vue.mixin({
    beforeCreate() {
      if (isDef(this.$options.monitor)) {
        this._monitorRoot = this
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        this._monitor = this.$options.monitor!
        this._monitor.init(this)
      } else {
        this._monitorRoot = (this.$parent && this.$parent._monitorRoot) || this
      }
    },
  })

  Vue.use(directive)

  Object.defineProperty(Vue.prototype, '$monitor', {
    get() {
      return this._monitorRoot._monitor
    },
  })
}
