import { useEffect } from "react";
import { trackActivity } from "../../utils/session.js";
import { CMicroAppHost } from "../../utils/micro-frontend/host.js";
import { getMicroFrontEndAppConfig } from "../../utils/micro-frontend/index.js";
import { APP_CONTAINER_ID_PREFIX } from "../micro-app/const.js";
const addBaseTag = (id, documentEle) => {
  const { hostUrl, manifestPath } = getMicroFrontEndAppConfig({
    id
  });
  if (!hostUrl || !manifestPath)
    throw new Error("hostUrl or manifestPath is not defined");
  const base = documentEle.createElement("base");
  base.href = new URL(manifestPath, hostUrl).href;
  documentEle.getElementsByTagName("head")[0].appendChild(base);
};
const updateContainerId = (id, documentEle) => {
  const ele = documentEle.getElementById(APP_CONTAINER_ID_PREFIX);
  if (ele) {
    ele.id = `${ele.id}${id}`;
    ele.dataset.testid = ele.id;
  }
};
const useFrameLoaded = ({ id, documentEle }) => {
  useEffect(() => {
    if (!documentEle) return () => {
    };
    const host = CMicroAppHost.getInstance();
    addBaseTag(id, documentEle);
    updateContainerId(id, documentEle);
    const removeUserActivityListener = trackActivity(documentEle, async () => {
      await host.renewSessionTimer();
    });
    return () => {
      if (removeUserActivityListener) {
        removeUserActivityListener();
      }
    };
  }, [id, documentEle]);
};
export {
  useFrameLoaded
};
