import { computed, unref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import { ResizeObserver } from '@juggle/resize-observer';

var useResize = (function (triggerRef, callback, disabled) {
  let immediate = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  const disabledRef = computed(() => unref(disabled));
  const handleResize = function () {
    if (disabledRef.value) {
      return;
    }
    if (!immediate) {
      immediate = true;
      return;
    }
    for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
      params[_key] = arguments[_key];
    }
    callback === null || callback === void 0 || callback(...params);
  };
  const ro = new ResizeObserver(handleResize);
  let observedDom = null;
  const handle = dom => {
    if (observedDom) {
      ro.unobserve(observedDom);
    }
    if (dom) {
      try {
        ro.observe(dom);
        observedDom = dom;
      } catch (err) {
        console.warn('[useResize] observe dom fail, dom:', dom, ' dom.parentNode:', dom.parentNode, ' error:', err);
      }
    }
  };
  onMounted(() => {
    watch(triggerRef, () => {
      nextTick(() => {
        handle(triggerRef.value);
      });
    }, {
      immediate: true
    });
  });
  onBeforeUnmount(() => {
    if (observedDom) {
      ro.unobserve(observedDom);
    }
    ro.disconnect();
    observedDom = null;
  });
});

export { useResize as default };
