const RESIZE_OBSERVE = 'RESIZE_OBSERVE'

const resizeDOM = (el, binding) => {
  const resizeHandler = binding.value
  const resizeObserver = new ResizeObserver((entries) => {
    entries.length > 0 && resizeHandler(entries[0])
  })
  resizeObserver.observe(el)
  return resizeObserver
}

const ResizeDomDirective = {
  mounted(el, binding) {    
    el[RESIZE_OBSERVE] = resizeDOM(el, binding)
  },

  unmounted(el) {
    if (el && el[RESIZE_OBSERVE]) {
      const resizeObserver= el[RESIZE_OBSERVE]
      resizeObserver.unobserve(el)
      resizeObserver.disconnect()
      delete el[RESIZE_OBSERVE]
    }
  }
}

export default ResizeDomDirective
