import { ref, onUnmounted } from 'vue';


function useClick(options = { delay: 300, click: null, dbclick: null }) {
  const element = ref(null);
  const timer = ref(null);

  function handleClick(event, ...rest) {
    if (element.value !== event.target) {
      element.value = event.target;
      clearTimer();
      timer.value = setTimeout(() => {
        typeof options.click === 'function' && options.click(...rest);
        element.value = null
      }, options.delay)
    } else {
      clearTimer();
      typeof options.dbclick === 'function' && options.dbclick(...rest);
      element.value = null
    }
  }

  function clearTimer() {
    timer.value && clearTimeout(timer.value);
  }

  onUnmounted(() => {
    clearTimer();
    element.value = null;
  });
  return handleClick;
}

export default useClick;