import { doShowLog } from "./main";
import { IAutoMdData } from "./interface.ts";
import { logClick } from "./manual.ts";

// 如果点击埋点和跳转埋点只能添加一个的话，两个mapper可以合并成为一个mapper
const clickMapper = new Map();

const generatorClick = (item: IAutoMdData) => {
  const ele = document.querySelector(item.ele);
  if (!!ele && !clickMapper.get(item.ele)) {
    const handler = logClick.bind(null, item.data);
    clickMapper.set(item.ele, {
      ele,
      handler,
    });
    ele.addEventListener("click", handler);
  }
  // 元素不在文档，绑定了点击埋点(其实不是不在文档，而是比如class改变导致选择器无法再选中而已)
  // 那么需要将点击埋点移除
  if (!ele && clickMapper.get(item.ele)) {
    console.log("元素不在文档");
    clickMapper.get(item.ele).ele.removeEventListener("click", clickMapper.get(item.ele).handler);
    clickMapper.set(item.ele, null);
  }
}

export const MDAuto = (config: { show: IAutoMdData[]; click: IAutoMdData[]; }) => {
  const { show, click } = config;
  doShowLog(show);
  if (click && click.length) {
    click.forEach((item) => generatorClick(item));

    // 每次dom 插入节点的时候重新检测
    const observer = new MutationObserver(() => {
      click.forEach((item) => generatorClick(item));
    });
    observer.observe(document, {
      attributes: true,
      childList: true,
      subtree: true,
    });
  }
}
