import { getCurrentInstance, onBeforeUnmount, onDeactivated } from 'vue'

import { vmIsDestroyed } from '../../utils/private.vm/vm.js'
import { noop } from '../../utils/event/event.js'

/*
 * Usage:
 *    registerTimeout(fn[, delay])
 *    removeTimeout()
 */

export default function useTimeout() {
  if (__QUASAR_SSR_SERVER__) {
    return {
      removeTimeout: noop,
      registerTimeout: noop
    }
  }

  let timer = null
  const vm = getCurrentInstance()

  function removeTimeout() {
    if (timer !== null) {
      clearTimeout(timer)
      timer = null
    }
  }

  onDeactivated(removeTimeout)
  onBeforeUnmount(removeTimeout)

  return {
    removeTimeout,

    registerTimeout(fn, delay) {
      removeTimeout()

      if (!vmIsDestroyed(vm)) {
        timer = setTimeout(() => {
          timer = null
          fn()
        }, delay)
      }
    }
  }
}
