import { MessageType } from "@elliemae/microfe-common";
const applicationScriptingObject = {
  object: {
    events: [],
    functions: [
      "closeModal",
      "extend",
      "getApplicationContext",
      "getCapabilities",
      "getCompanySettings",
      "getDescriptor",
      "getPersonaAccess",
      "getPoliciesDetails",
      "getUserAccessRights",
      "hideSpinner",
      "keepSessionAlive",
      "log",
      "navigate",
      "open",
      "openModal",
      "performAction",
      "print",
      "showError",
      "showSpinner",
      "supportsAction",
      "supportsNavigateTo"
    ],
    objectId: "application",
    objectType: "Object"
  },
  type: "object"
};
const authScriptingObject = {
  object: {
    events: [],
    functions: ["getAccessToken", "createAuthCode", "getUser"],
    objectId: "auth",
    objectType: "Object"
  },
  type: "object"
};
const hostObjects = {
  application: applicationScriptingObject,
  auth: authScriptingObject
};
const getOrigin = (url) => {
  if (!url || url === "about:blank") return "*";
  try {
    const { origin } = new URL(url);
    return origin === "null" || !origin ? url : origin;
  } catch (e) {
    const { origin } = new URL(url, document.baseURI);
    return origin;
  }
};
const postMessage = ({
  srcWindow,
  targetWindow,
  message
}) => {
  targetWindow.dispatchEvent(
    new MessageEvent("message", {
      source: srcWindow,
      origin: getOrigin(srcWindow.location.href),
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      data: {
        source: "elli:remoting",
        ...message
      }
    })
  );
};
const setupHost = (hostWindow) => {
  const onMessage = ({ data }) => {
    if (data?.type !== MessageType.ObjectGet) return;
    const scriptingObject = hostObjects[data?.body?.objectId ?? ""] ?? null;
    if (scriptingObject)
      postMessage({
        srcWindow: hostWindow,
        targetWindow: window,
        message: {
          body: scriptingObject,
          type: "elli:remoting:response",
          requestId: data.requestId
        }
      });
  };
  hostWindow?.addEventListener?.("message", onMessage);
  return () => hostWindow?.removeEventListener?.("message", onMessage);
};
export {
  applicationScriptingObject,
  authScriptingObject,
  postMessage,
  setupHost
};
