import { getCurrentInstance, onActivated, onDeactivated, onMounted, onUnmounted, ref } from 'vue'
import { debounce } from '@/utils'

export default function() {
  const $_sidebarElm = ref(null)
  const $_resizeHandler = ref(null)

  let proxy

  onMounted(() => {
    initListener()
    proxy = getCurrentInstance()
  })

  onActivated(() => {
    if (!$_resizeHandler.value) {
      // avoid duplication init
      initListener()
    }

    // when keep-alive chart activated, auto resize
    proxy.exposed.resize()
  })

  onUnmounted(() => {
    destroyListener()
  })

  onDeactivated(() => {
    destroyListener()
  })

  // use $_ for mixins properties
  function $_sidebarResizeHandler(e) {
    if (e.propertyName === 'width') {
      $_resizeHandler()
    }
  }

  function initListener() {
    $_resizeHandler.value = debounce(() => {
      proxy.exposed.resize()
    }, 100)
    window.addEventListener('resize', $_resizeHandler.value)

    $_sidebarElm.value = document.getElementsByClassName('sidebar-container')[0]
    $_sidebarElm.value && $_sidebarElm.value.addEventListener('transitionend', $_sidebarResizeHandler)
  }

  function destroyListener() {
    window.removeEventListener('resize', $_resizeHandler.value)
    $_resizeHandler.value = null

    $_sidebarElm.value && $_sidebarElm.value.removeEventListener('transitionend', $_sidebarResizeHandler)
  }
}
