import type { DirectiveBinding, ObjectDirective } from 'vue'

const disabled: ObjectDirective = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    updateDisabled(el, binding.value)
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    updateDisabled(el, binding.value)
  },
}

function updateDisabled(el: HTMLElement, value: boolean) {
  if (value) {
    if ('disabled' in el) {
      el.disabled = true
    } else {
      el.setAttribute('disabled', 'true')
      el.style.pointerEvents = 'none'
      el.style.opacity = '0.6'
      el.style.cursor = 'not-allowed'
    }
  } else {
    if ('disabled' in el) {
      el.disabled = false
    } else {
      el.removeAttribute('disabled')
      el.style.pointerEvents = ''
      el.style.opacity = ''
      el.style.cursor = ''
    }
  }
}

export default disabled
