import { listener } from "@/utils/event";
import { installGlobalVar, stackVar, useStage } from "./use-global-vars";
import { Pos } from "@/utils/math";

type PasteHandlers = Record<
  string,
  | { handler: (position: Pos, data: string, meta: string) => void; type: "string" }
  | { handler: (position: Pos, data: File, meta: string) => void; type: "file" }
>;
export const usePaste = installGlobalVar(() => {
  const stage = useStage();
  const handlers = stackVar<PasteHandlers>({});
  const pasteHandler = (ev: ClipboardEvent) => {
    if (ev.target !== document.body && (ev.target as any).id !== 'dom-mount') return;

    const pos = stage.value?.getNode().pointerPos;
    const clipboardData = ev.clipboardData;
    if (!clipboardData || !pos) return;

    ev.preventDefault();
    for (const item of clipboardData.items) {
      const handMetas = Object.keys(handlers.value)
      for (const handMeta of handMetas) {
        if (item.type.includes(handMeta)) {
          const handleItem = handlers.value[handMeta]
          if (handleItem.type === 'file') {
            const file = item.getAsFile()
            file && handleItem.handler(pos, file, item.type)
          } else {
            item.getAsString((str) => {
              str.trim() && handleItem.handler(pos, str.trim(), item.type)
            });
          }
        }
      }
    }
  };

  return {
    var: handlers,
    onDestroy: listener(window, "paste", pasteHandler),
  };
});
