"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var host_exports = {};
__export(host_exports, {
  CMicroAppHost: () => CMicroAppHost
});
module.exports = __toCommonJS(host_exports);
var import_pubsub_js = require("pubsub-js");
var import_lodash = require("lodash");
var import_pui_theme = require("@elliemae/pui-theme");
var import_pui_analytics_so = require("@elliemae/pui-analytics-so");
var import_store = require("../../data/store.js");
var import_actions = require("../../data/wait-message/actions.js");
var import_error = require("../../data/error/index.js");
var import_actions2 = require("../../data/logout/actions.js");
var import_config = require("../app-config/config.js");
var import_app_config = require("../app-config/index.js");
var import_history2 = require("../history.js");
var import_console_logger = require("../console-logger.js");
var import_logger = require("../logger.js");
var import_constants = require("../constants.js");
var import_window = require("../window.js");
var import_logrocket = require("../logrocket.js");
var import_session = require("../session.js");
var import_app_bridge = require("./app-bridge.js");
var import_ssf_host2 = require("./ssf-host.js");
class CMicroAppHost {
  static instance;
  logger;
  /**
   * LogRocket instance
   */
  #logRocket;
  appId;
  props;
  activeGuests;
  onInit;
  onRenewSessionTimer;
  throttleRenewSessionTimer;
  scriptingObjects;
  #ssfHostRef;
  #appBridge = null;
  // eslint-disable-next-line max-statements
  constructor(params) {
    this.appId = (0, import_config.getAppConfigValue)("appId");
    this.onInit = params?.onInit;
    this.logger = params?.logger || import_console_logger.consoleLogger;
    (0, import_logger.setLogger)(this.logger);
    this.#logRocket = params?.logRocket ?? window.emui?.logRocket;
    (0, import_logrocket.setLogRocket)(this.#logRocket);
    this.onRenewSessionTimer = params?.onRenewSessionTimer;
    this.props = {
      systemVersion: params?.version ?? "latest",
      history: params?.history ?? import_history2.browserHistory,
      theme: params?.theme ?? (0, import_pui_theme.getDefaultTheme)()
    };
    this.activeGuests = {};
    if (params?.ssfHostRef) (0, import_ssf_host2.setSSFHost)(params.ssfHostRef);
    this.#ssfHostRef = (0, import_ssf_host2.getSSFHost)();
    const analyticsObj = params?.analytics ?? new import_pui_analytics_so.Analytics({ logger: this.logger });
    this.scriptingObjects = {
      analytics: analyticsObj,
      ...params?.scriptingObjects ?? {}
    };
    this.getProps = this.getProps.bind(this);
    this.getLogger = this.getLogger.bind(this);
    this.getGuests = this.getGuests.bind(this);
    this.getGuest = this.getGuest.bind(this);
    this.getObject = this.getObject.bind(this);
    this.renewSessionTimer = this.renewSessionTimer.bind(this);
    this.setSystemVersion = this.setSystemVersion.bind(this);
    this.sendBAEvent = this.sendBAEvent.bind(this);
    this.throttleRenewSessionTimer = (0, import_lodash.throttle)(
      async () => {
        await (0, import_session.renewSession)();
        if (this.onRenewSessionTimer) this.onRenewSessionTimer();
      },
      import_constants.SESSION_RENEWAL_INTERVAL,
      {
        leading: true
      }
    );
    (0, import_app_config.loadAppConfig)().then(() => {
      (0, import_app_bridge.getAppBridge)().then((appBridge) => {
        this.#appBridge = appBridge;
        if (this.onInit) this.onInit(this.props);
      }).catch((ex) => {
        throw ex;
      });
    }).catch(() => {
    });
    (0, import_pui_analytics_so.updateBAEventParameters)({ appId: this.appId });
  }
  static getInstance(params) {
    if (!this.instance) {
      this.instance = new CMicroAppHost(params);
    }
    return this.instance;
  }
  static isInitialized() {
    return !!this.instance;
  }
  getProps() {
    return this.props;
  }
  getLogger() {
    return this.logger;
  }
  getItem(key) {
    return (0, import_window.getWindow)().sessionStorage.getItem(key);
  }
  setItem(key, value) {
    (0, import_window.getWindow)().sessionStorage.setItem(key, value);
  }
  getGuests() {
    return this.activeGuests;
  }
  getGuest(id) {
    return this.activeGuests[id] ? this.activeGuests[id] : null;
  }
  publish(message, data) {
    return (0, import_pubsub_js.publish)(message, data);
  }
  // eslint-disable-next-line @typescript-eslint/ban-types
  subscribe(message, func) {
    return (0, import_pubsub_js.subscribe)(message, func);
  }
  unsubscribe(token) {
    (0, import_pubsub_js.unsubscribe)(token);
  }
  navigate(url, state) {
    if (url) this.props.history.push(url, state);
  }
  openWaitMessage() {
    const store = (0, import_store.getStore)();
    if (store) store.dispatch(import_actions.waitMessage.open());
  }
  closeWaitMessage() {
    const store = (0, import_store.getStore)();
    if (store) store.dispatch(import_actions.waitMessage.close());
  }
  openErrorBanner(message) {
    const store = (0, import_store.getStore)();
    if (store) store.dispatch(import_error.actions.set({ description: message }));
  }
  getAuthToken() {
    return (0, import_window.getWindow)().sessionStorage.getItem("Authorization");
  }
  renewAuthToken() {
    return (0, import_window.getWindow)().sessionStorage.getItem("Authorization");
  }
  logout() {
    const store = (0, import_store.getStore)();
    if (store) store.dispatch(import_actions2.logout.confirm());
  }
  // eslint-disable-next-line @typescript-eslint/require-await
  async renewSessionTimer() {
    this.throttleRenewSessionTimer();
  }
  getBreakpoint() {
    return (0, import_window.getCurrentBreakpoint)();
  }
  getViewportSize() {
    return (0, import_window.getViewportSize)();
  }
  onResizeEvent(eventHandler) {
    return (0, import_pubsub_js.subscribe)(
      import_constants.HOST_WINDOW_RESIZED,
      (msg, data) => eventHandler(data)
    );
  }
  onBreakpointChangeEvent(eventHandler) {
    return (0, import_pubsub_js.subscribe)(
      import_constants.HOST_WINDOW_BREAKPOINT_CHANGED,
      (msg, data) => eventHandler(data)
    );
  }
  setSystemVersion(version = "latest") {
    window.emui.version = version;
    this.props.systemVersion = version;
  }
  sendBAEvent(data) {
    this.scriptingObjects.analytics.sendBAEvent(data).catch(() => {
    });
  }
  // eslint-disable-next-line @typescript-eslint/require-await
  async getObject(name) {
    return this.scriptingObjects[name];
  }
  /**
   * add scripting object for child microapp to use
   * @param so - The scripting object to be added.
   * @param params - Optional parameters for adding the scripting object.
   */
  addScriptingObject(so, params) {
    if (this.#appBridge) {
      this.#appBridge.addScriptingObject(so, params);
    }
    this.#ssfHostRef.addScriptingObject(so, params);
  }
  /**
   * dispatch event to child microapp
   * @param {DispatchEventParams<EventId, Params>} params - event parameters
   * @returns {Promise<any>} A promise that resolves with the combined results of dispatched events.
   */
  async dispatchEvent(params) {
    if (this.#appBridge) {
      const [appBridgeResult, ssfResult] = await Promise.all([
        this.#appBridge.dispatchEvent(params),
        this.#ssfHostRef.dispatchEvent(params)
      ]);
      if (Array.isArray(appBridgeResult) && Array.isArray(ssfResult)) {
        return appBridgeResult.concat(ssfResult);
      }
      return Promise.resolve();
    }
    return this.#ssfHostRef.dispatchEvent(params);
  }
  /**
   * removes scripting object from child microapp use
   * @param objectId unique id of the scripting object
   */
  removeScriptingObject(objectId) {
    if (this.#appBridge) {
      this.#appBridge.removeScriptingObject(objectId);
    }
    this.#ssfHostRef.removeScriptingObject(objectId);
  }
}
