"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 session_exports = {};
__export(session_exports, {
  addEventListeners: () => addEventListeners,
  initSessionMonitoring: () => initSessionMonitoring,
  renewSession: () => renewSession,
  resetUserIdleTime: () => resetUserIdleTime,
  stopSessionMonitoring: () => stopSessionMonitoring,
  subscribeToResetSession: () => subscribeToResetSession,
  subscribeToSessionExpiry: () => subscribeToSessionExpiry,
  subscribeToSessionExpiryWarning: () => subscribeToSessionExpiryWarning,
  trackActivity: () => trackActivity
});
module.exports = __toCommonJS(session_exports);
var import_lodash = require("lodash");
var import_loginParams = require("./auth/loginParams.js");
var import_helper = require("./auth/helper.js");
var import_auth = require("../api/auth/index.js");
var import_logger = require("./logger.js");
var import_log_records = require("./log-records.js");
var import_auth2 = require("./auth/index.js");
var import_config = require("./app-config/config.js");
var import_constants = require("./constants.js");
let lastUserActivityTimeStamp = Date.now();
const warnListeners = [];
const expiryListeners = [];
const resetListeners = [];
const userInteractionEvents = ["click", "scroll", "keypress", "touchstart"];
let sessionExpiryWarningNotified = false;
let timerHandle;
let sessionExpiryWarningNotifiedAt;
const resetUserIdleTime = (resetWarningModal = false) => {
  sessionExpiryWarningNotified = false;
  sessionExpiryWarningNotifiedAt = null;
  lastUserActivityTimeStamp = Date.now();
  Promise.resolve().then(() => {
    resetListeners.forEach((listener) => listener(resetWarningModal));
  }).catch(() => {
  });
};
const renewSession = async () => {
  const loginParams = (0, import_loginParams.getLoginParams)();
  try {
    resetUserIdleTime(true);
    if (loginParams?.clientId) {
      const authToken = (0, import_helper.getAuthorizationHeader)();
      if (!authToken)
        throw new Error("Authorization token not found to extend session");
      const accessToken = authToken.split(" ")[1];
      await (0, import_auth.introspectToken)({ clientId: loginParams.clientId, accessToken });
    }
  } catch (e) {
    (0, import_logger.getLogger)()?.error({
      ...import_log_records.logRecords.SESSION_RENEWAL_FAILED,
      exception: e
    });
    await (0, import_auth2.endSession)({ ...loginParams, skipRevoke: true });
  }
};
const renewSessionAtInterval = (0, import_lodash.throttle)(
  renewSession,
  import_constants.SESSION_RENEWAL_INTERVAL,
  {
    leading: true
  }
);
const isPastWarningTime = (warnInterval = (0, import_config.getAppConfigValue)("sessionTimeoutWarnInterval") || import_constants.SESSION_TIMEOUT_INTERVAL.WARN) => Date.now() - lastUserActivityTimeStamp > warnInterval;
const isPastSessionTimeoutTime = (sessionTimeout = (0, import_config.getAppConfigValue)("sessionTimeoutInterval") || import_constants.SESSION_TIMEOUT_INTERVAL.EXPIRY) => Date.now() - lastUserActivityTimeStamp > sessionTimeout;
const notifySessionExpiryWarning = () => {
  sessionExpiryWarningNotified = true;
  sessionExpiryWarningNotifiedAt = Date.now();
  Promise.resolve().then(() => {
    warnListeners.forEach(
      (listener) => listener(sessionExpiryWarningNotifiedAt)
    );
    userInteractionEvents.forEach((eventType) => {
      document.removeEventListener(eventType, renewSessionAtInterval);
    });
  }).catch(() => {
  });
};
const notifySessionExpiry = () => Promise.resolve().then(() => {
  expiryListeners.forEach((listener) => listener());
});
const stopSessionMonitoring = () => {
  userInteractionEvents.forEach((eventType) => {
    document.removeEventListener(eventType, renewSessionAtInterval);
  });
  clearInterval(timerHandle);
  warnListeners.length = 0;
  expiryListeners.length = 0;
};
const monitorSessionEvents = () => {
  if (isPastSessionTimeoutTime()) {
    notifySessionExpiry().then(() => {
      stopSessionMonitoring();
    }).catch(() => {
    });
  } else if (!sessionExpiryWarningNotified && isPastWarningTime())
    notifySessionExpiryWarning();
};
const removeListeners = (arr, cb) => {
  const idx = arr.findIndex((r) => r === cb);
  if (idx > -1) {
    arr.splice(idx, 1);
  }
};
const addEventListeners = () => {
  userInteractionEvents.forEach((eventType) => {
    document.addEventListener(eventType, renewSessionAtInterval);
  });
};
const initSessionMonitoring = () => {
  addEventListeners();
  timerHandle = setInterval(monitorSessionEvents, 1e3);
};
const subscribeToSessionExpiryWarning = (onSessionExpiryWarn) => {
  warnListeners.push(onSessionExpiryWarn);
  return removeListeners.bind(null, warnListeners, onSessionExpiryWarn);
};
const subscribeToSessionExpiry = (onSessionExpiry) => {
  expiryListeners.push(onSessionExpiry);
  return removeListeners.bind(null, expiryListeners, onSessionExpiry);
};
const subscribeToResetSession = (onResetListener) => {
  resetListeners.push(onResetListener);
  return removeListeners.bind(null, resetListeners, onResetListener);
};
const trackActivity = (element, cb) => {
  if (!element) return () => {
  };
  const thorttledCb = (0, import_lodash.throttle)(cb, import_constants.SESSION_RENEWAL_INTERVAL, { leading: true });
  userInteractionEvents.forEach(
    (r) => element.addEventListener(r, thorttledCb)
  );
  return () => {
    userInteractionEvents.forEach((r) => element.removeEventListener(r, cb));
    userInteractionEvents.forEach(
      (r) => element.removeEventListener(r, thorttledCb)
    );
  };
};
