const appId = "loanapp";
const appName = "Loan App";
const appElementId = `pui-app-container-${appId}`;
const pipelinePath = "/pipeline";
const pipelineLinkText = "Pipeline";
const getWindow = () => {
  let winObj = window;
  try {
    window.parent.document;
    winObj = window.parent;
  } catch (err) {
  }
  winObj.__TEST__ = winObj.__TEST__ ?? {};
  winObj.__TEST__.logs = winObj.__TEST__.logs ?? [];
  winObj.__TEST__[appId] = [];
  winObj.addTestLog = (log) => {
    winObj.__TEST__.logs.push(log);
  };
  winObj.addAppLog = (log) => {
    winObj.__TEST__[appId].push(log);
  };
  return winObj;
};
let host = null;
let parentHistory = null;
let logger = null;
const browserWindow = getWindow(appId);
window.__TEST__ = {};
const setFrameSize = () => {
  const { document: document2 } = window;
  const iframeBody = document2.body;
  const iframeHTML = document2.documentElement;
  const size = {
    height: Math.max(
      iframeBody.scrollHeight,
      iframeBody.offsetHeight,
      iframeHTML.offsetHeight
    ),
    width: Math.max(
      iframeBody.scrollWidth,
      iframeBody.offsetWidth,
      iframeHTML.offsetWidth
    )
  };
  host.setAppWindowSize?.({
    appId,
    size
  });
};
window.emui = window.emui || { uuid: crypto.randomUUID() };
window.emui.app = {
  uuid: window.emui.uuid,
  init: async (options) => {
    browserWindow.addTestLog(`${appId} initializing`);
    host = options.host;
    parentHistory = options.history;
    logger = options.logger;
    window.__TEST__.initOptions = options;
    setFrameSize();
  },
  mount: async (options) => {
    browserWindow.addTestLog(`${appId} mounting`);
    window.__TEST__.mountOptions = options;
    const appContainer = document.getElementById(appElementId);
    if (appContainer) {
      const mainElement = document.createElement("main");
      appContainer.appendChild(mainElement);
      const pageHeaderEle = document.createElement("h1");
      pageHeaderEle.textContent = appName;
      mainElement.appendChild(pageHeaderEle);
      const contentEle = document.createElement("p");
      contentEle.textContent = "Go to ";
      mainElement.appendChild(contentEle);
      const linkEle = document.createElement("a");
      linkEle.href = "#";
      linkEle.onclick = () => {
        parentHistory?.push?.(pipelinePath);
      };
      linkEle.textContent = pipelineLinkText;
      contentEle.appendChild(linkEle);
      browserWindow.addTestLog(`${appId} mounted`);
      const loanObj = await host.getObject("loan");
      if (loanObj) {
        const loanData = await loanObj.all();
        browserWindow.addAppLog(
          `loan.all():returns:${JSON.stringify(loanData)}`
        );
        host.subscribe({
          eventId: "loan.precommit",
          callback: (data) => {
            browserWindow.addAppLog(
              `loan.precommit:event:received: eventName:${data.eventName} eventParams:${JSON.stringify(data.eventParams)}`
            );
            return true;
          }
        });
        await loanObj.commit();
      }
    } else {
      throw new Error(
        `App container element with id ${appElementId} not found`
      );
    }
  },
  unmount: () => {
    browserWindow.addTestLog(`${appId} unmounting`);
    const appContainer = document.getElementById(appElementId);
    if (appContainer) {
      appContainer.removeChild(appContainer.getElementsByTagName("main")[0]);
    }
    browserWindow.addTestLog(`${appId} unmounted`);
    return Promise.resolve();
  }
};
browserWindow.emui?.registerApp?.({ appId, app: window.emui.app });
