import { ref, watch, unref } from 'vue';
import { useDebounceFn, useThrottleFn } from '@vueuse/core';

function useEventListener(_ref) {
  var _ref$el = _ref.el,
    el = _ref$el === void 0 ? window : _ref$el,
    name = _ref.name,
    listener = _ref.listener,
    options = _ref.options,
    _ref$autoRemove = _ref.autoRemove,
    autoRemove = _ref$autoRemove === void 0 ? true : _ref$autoRemove,
    _ref$isDebounce = _ref.isDebounce,
    isDebounce = _ref$isDebounce === void 0 ? true : _ref$isDebounce,
    _ref$wait = _ref.wait,
    wait = _ref$wait === void 0 ? 80 : _ref$wait;
  var remove = function remove() {};
  var isAddRef = ref(false);
  if (el) {
    var element = ref(el);
    var handler = isDebounce ? useDebounceFn(listener, wait) : useThrottleFn(listener, wait);
    var realHandler = wait ? handler : listener;
    var removeEventListener = function removeEventListener(e) {
      isAddRef.value = true;
      e.removeEventListener(name, realHandler, options);
    };
    var addEventListener = function addEventListener(e) {
      return e.addEventListener(name, realHandler, options);
    };
    var removeWatch = watch(element, function (v, _ov, cleanUp) {
      if (v) {
        !unref(isAddRef) && addEventListener(v);
        cleanUp(function () {
          autoRemove && removeEventListener(v);
        });
      }
    }, {
      immediate: true
    });
    remove = function remove() {
      removeEventListener(element.value);
      removeWatch();
    };
  }
  return {
    removeEvent: remove
  };
}

export { useEventListener };
