import "./intersection-observer.polyfill.js";
import "intersection-observer";
import { IAutoMdData } from "./interface.ts";
import { logExposure } from "./manual.ts";

const showedMapper = {};

const intersectionObservers: IntersectionObserver[] = [];

function registryIntersectionObserver(items: any[]) {
  for (const observer of intersectionObservers) {
    observer.disconnect();
  }
  intersectionObservers.splice(0);

  items.forEach((item) => {
    if (typeof item.ele === "string") {
      generatorShow(item);
    } else {
      item.ele.map((eleChild: any) => generatorShow({ ...item, ele: eleChild }));
    }
  });
}

const generatorShow = (item: IAutoMdData) => {

  const { once = true, ele, data } = item;

  const element = document.querySelector(item.ele);

  // 目标元素在dom中则处理
  if (element) {
    const observer = new IntersectionObserver((changes) => {
      changes.forEach((change) => {
        // 如果出现在页面中
        if (change.intersectionRatio > 0) {
          // 已经曝光过了
          if (showedMapper[ele]) return;

          showedMapper[ele] = true;

          observer.unobserve(change.target);

          logExposure(data);

        } else {
          // 消失在视口
          if (!once) {
            // 如果需要曝光多次就移除
            showedMapper[ele] = false;
          }
        }
      });
    }, {});

    // 为目标元素注册IntersectionObserver
    element && observer.observe(element);

    intersectionObservers.push(observer)
  }
};

export function doShowLog(items: IAutoMdData[]) {
  // 先注册一次
  registryIntersectionObserver(items);

  // 每次dom 插入节点的时候重新检测
  const observer = new MutationObserver(function () {
    registryIntersectionObserver(items);
  });
  observer.observe(document, { childList: true, subtree: true });
}
