import _Vue, { DirectiveFunction, VueConstructor, PluginObject } from 'vue'
import { MonitorElement } from '.'
import { monitorElement, unmonitorElement } from './event'

interface MonitorDirectiveFunction extends DirectiveFunction, PluginObject<any> {}

export const directive: MonitorDirectiveFunction = (el: MonitorElement, { value }, vNode) => {
  if (!value) {
    unmonitorElement(el)
    delete el.__monitor
    delete el.dataset.monitor
    delete el.__monitor_actions
    return
  }
  const actions = Object.keys(value)
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  el.__monitor = vNode.componentInstance!.$monitor
  el.__monitor_actions = actions
  monitorElement(el)
  el.dataset.monitor = JSON.stringify(value)
}

directive.install = (Vue: VueConstructor<_Vue>) => {
  Vue.directive('monitor', directive)
}
