import { listener } from "../../utils/event.ts";
import { installGlobalVar, useStage } from "./use-global-vars.ts";
import { nextTick, ref, watchEffect } from "vue";

export const useListener = <
  T extends HTMLElement,
  K extends keyof HTMLElementEventMap
>(
  eventName: K,
  callback: (
    this: T,
    ev: HTMLElementEventMap[K],
    stageDOM: HTMLDivElement
  ) => any,
  target?: HTMLElement | Window
) => {
  const stage = useStage();
  return watchEffect((onCleanup) => {
    if (stage.value) {
      const $stage = stage.value!.getStage();
      const dom = $stage.container() as any;
      onCleanup(
        listener(target || dom, eventName, function (ev) {
          callback.call(this, ev, dom);
        })
      );
    }
  });
};

export const useGlobalResize = installGlobalVar(() => {
  const stage = useStage();
  const size = ref<{ width: number; height: number }>();
  const setSize = () => {
    const container = stage.value?.getStage().container()
    if (container) {
      container.style.setProperty('display', 'none')
    }

    const dom = stage.value!.getNode().container().parentElement!;
    size.value = {
			width: dom.offsetWidth,
			height: dom.offsetHeight
		}
    if (container) {
      container.style.removeProperty('display')
    }
  };
  const stopWatch = watchEffect(() => {
    if (stage.value) {
      setSize();
      nextTick(() => stopWatch());
    }
  });
  useListener("resize", setSize, window);

  return {
    updateSize: setSize,
    size,
  }
}, Symbol('resize'))

export const useResize = () => useGlobalResize().size;
