'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.iterator.js');
require('core-js/modules/es.array.join.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/es.promise.js');
require('core-js/modules/es.regexp.exec.js');
require('core-js/modules/es.string.iterator.js');
require('core-js/modules/es.string.replace.js');
require('core-js/modules/web.dom-collections.for-each.js');
require('core-js/modules/web.dom-collections.iterator.js');
require('core-js/modules/web.url.js');
require('core-js/modules/web.url.to-json.js');
require('core-js/modules/web.url-search-params.js');
var React = require('react');
var PropTypes = require('prop-types');
var classnames = require('classnames');
var react = require('@carbon/react');
var Settings = require('../../../constants/Settings.js');
var IdleTimer = require('../util/IdleTimer.js');
var suiteHeaderConstants = require('../suiteHeaderConstants.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _asyncToGenerator__default = /*#__PURE__*/_interopDefault(_asyncToGenerator);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefault(_regeneratorRuntime);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var IdleLogoutConfirmationModalIdleTimeoutPropTypes = {
  /** User inactivity timeout, in seconds */
  timeout: PropTypes__default.default.number,
  /** Countdown start value, in seconds, for the logout confirmation modal */
  countdown: PropTypes__default.default.number,
  /** Cookie name for cross-tab support */
  cookieName: PropTypes__default.default.string
};
var IdleLogoutConfirmationModalRoutePropTypes = {
  /** Route for the logout redirect page when Log out button is clicked */
  logout: PropTypes__default.default.string,
  /** Route for the logout redirect page when user is logged out due to inactivity */
  logoutInactivity: PropTypes__default.default.string,
  /** Cookie domain for cross-tab support */
  domain: PropTypes__default.default.string
};
var IdleLogoutConfirmationModalI18NPropTypes = {
  sessionTimeoutModalHeading: PropTypes__default.default.string,
  sessionTimeoutModalBody: PropTypes__default.default.string,
  sessionTimeoutModalLogoutButton: PropTypes__default.default.string,
  sessionTimeoutModalStayLoggedInButton: PropTypes__default.default.string
};
var defaultProps = {
  isAdminView: null,
  appId: null,
  workspaceId: null,
  className: null,
  idleTimeoutData: {
    timeout: 1800,
    // 30 minutes
    countdown: 30,
    // 30 seconds
    cookieName: '_user_inactivity_timeout'
  },
  routes: null,
  onRouteChange: function () {
    var _onRouteChange = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee() {
      return _regeneratorRuntime__default.default.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            return _context.abrupt("return", Promise.resolve(true));
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    function onRouteChange() {
      return _onRouteChange.apply(this, arguments);
    }
    return onRouteChange;
  }(),
  onStayLoggedIn: function onStayLoggedIn() {},
  i18n: {
    sessionTimeoutModalHeading: 'Session Timeout',
    sessionTimeoutModalBody: 'You will be logged out due to inactivity in {countdown} seconds.',
    sessionTimeoutModalLogoutButton: 'Log out',
    sessionTimeoutModalStayLoggedInButton: 'Stay logged in',
    closeButtonLabel: 'Close'
  }
};
var propTypes = {
  /** If true, include the originIsAdmin query param in the logout URL */
  isAdminView: PropTypes__default.default.bool,
  /** Application ID in suite */
  appId: PropTypes__default.default.string,
  /** Workspace ID in suite */
  workspaceId: PropTypes__default.default.string,
  /** Add class name to the rendered Modal component */
  className: PropTypes__default.default.string,
  /** User inactivity timeout data */
  idleTimeoutData: PropTypes__default.default.shape(IdleLogoutConfirmationModalIdleTimeoutPropTypes),
  /** URLs for routes used on this component */
  routes: PropTypes__default.default.shape(IdleLogoutConfirmationModalRoutePropTypes),
  /** Function called before any route change. Returns a Promise<Boolean>. False means the redirect will not happen. This function should never throw an error. */
  onRouteChange: PropTypes__default.default.func,
  /** Custom function that can be provided in case something else needs to be done when the "Stay logged in" button is clicked */
  onStayLoggedIn: PropTypes__default.default.func,
  /** I18N strings */
  i18n: PropTypes__default.default.shape(IdleLogoutConfirmationModalI18NPropTypes)
};
var IdleLogoutConfirmationModal = function IdleLogoutConfirmationModal(_ref) {
  var isAdminView = _ref.isAdminView,
    appId = _ref.appId,
    workspaceId = _ref.workspaceId,
    className = _ref.className,
    idleTimeoutData = _ref.idleTimeoutData,
    routes = _ref.routes,
    onRouteChange = _ref.onRouteChange,
    onStayLoggedIn = _ref.onStayLoggedIn,
    i18n = _ref.i18n;
  var mergedI18N = _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  var translate = React.useCallback(function (string, substitutions) {
    return substitutions.reduce(function (acc, _ref2) {
      var _ref3 = _slicedToArray__default.default(_ref2, 2),
        key = _ref3[0],
        val = _ref3[1];
      return acc.replace(key, val);
    }, string);
  }, []);

  // Append originHref query parameter (and, optionally, originIsAdmin, originWorkspaceId and originAppId) to the logout routes
  var logoutRoute = routes === null || routes === void 0 ? void 0 : routes.logout;
  try {
    var url = new URL(routes.logout);
    if (window.location.href) {
      url.searchParams.append('originHref', [window.location.protocol, '//', window.location.host, window.location.pathname].join(''));
    }
    if (appId) {
      url.searchParams.append('originAppId', appId);
    }
    if (workspaceId) {
      url.searchParams.append('originWorkspaceId', workspaceId);
    }
    if (isAdminView) {
      url.searchParams.append('originIsAdmin', isAdminView);
    }
    logoutRoute = url.href;
  } catch (e) {
    logoutRoute = routes === null || routes === void 0 ? void 0 : routes.logout;
  }
  var logoutInactivityRoute = routes === null || routes === void 0 ? void 0 : routes.logoutInactivity;
  try {
    var _url = new URL(routes.logoutInactivity);
    if (window.location.href) {
      _url.searchParams.append('originHref', [window.location.protocol, '//', window.location.host, window.location.pathname].join(''));
    }
    if (appId) {
      _url.searchParams.append('originAppId', appId);
    }
    if (workspaceId) {
      _url.searchParams.append('originWorkspaceId', workspaceId);
    }
    if (isAdminView) {
      _url.searchParams.append('originIsAdmin', isAdminView);
    }
    logoutInactivityRoute = _url.href;
  } catch (e) {
    logoutInactivityRoute = routes === null || routes === void 0 ? void 0 : routes.logoutInactivity;
  }

  // This state is just to force the recreation of the IdleTimer object in the useEffect below
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    restartIdleTimer = _useState2[0],
    setRestartIdleTimer = _useState2[1];
  // Countdown state. If countdown is greater than zero, logout confirmation dialog is going to be displayed
  var _useState3 = React.useState(0),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    logoutConfirmationCountdown = _useState4[0],
    setLogoutConfirmationCountdown = _useState4[1];
  // "Stay Logged in" button disabled state
  var _useState5 = React.useState(false),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    stayLoggedInButtonDisabled = _useState6[0],
    setStayLoggedInButtonDisabled = _useState6[1];
  // eslint-disable-next-line consistent-return
  React.useEffect(function () {
    if (idleTimeoutData && (idleTimeoutData === null || idleTimeoutData === void 0 ? void 0 : idleTimeoutData.timeout) > 0 && (routes === null || routes === void 0 ? void 0 : routes.domain) !== null && (routes === null || routes === void 0 ? void 0 : routes.domain) !== undefined) {
      var timer = new IdleTimer({
        timeout: idleTimeoutData.timeout,
        countdown: idleTimeoutData.countdown,
        cookieName: idleTimeoutData.cookieName,
        cookieDomain: routes.domain,
        onIdleTimeoutWarning: function onIdleTimeoutWarning(c) {
          setLogoutConfirmationCountdown(c);
        },
        onIdleTimeout: function () {
          var _onIdleTimeout = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee2() {
            var result;
            return _regeneratorRuntime__default.default.wrap(function _callee2$(_context2) {
              while (1) switch (_context2.prev = _context2.next) {
                case 0:
                  _context2.next = 2;
                  return onRouteChange(suiteHeaderConstants.SUITE_HEADER_ROUTE_TYPES.LOGOUT, logoutInactivityRoute);
                case 2:
                  result = _context2.sent;
                  if (result) {
                    window.location.href = logoutInactivityRoute;
                  }
                case 4:
                case "end":
                  return _context2.stop();
              }
            }, _callee2);
          }));
          function onIdleTimeout() {
            return _onIdleTimeout.apply(this, arguments);
          }
          return onIdleTimeout;
        }(),
        onCookieCleared: function () {
          var _onCookieCleared = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee3() {
            var result;
            return _regeneratorRuntime__default.default.wrap(function _callee3$(_context3) {
              while (1) switch (_context3.prev = _context3.next) {
                case 0:
                  _context3.next = 2;
                  return onRouteChange(suiteHeaderConstants.SUITE_HEADER_ROUTE_TYPES.LOGOUT, logoutRoute);
                case 2:
                  result = _context3.sent;
                  if (result) {
                    window.location.href = logoutRoute;
                  }
                case 4:
                case "end":
                  return _context3.stop();
              }
            }, _callee3);
          }));
          function onCookieCleared() {
            return _onCookieCleared.apply(this, arguments);
          }
          return onCookieCleared;
        }(),
        onRestart: function onRestart() {
          setLogoutConfirmationCountdown(0);
          onStayLoggedIn();
        }
      });
      return function () {
        setLogoutConfirmationCountdown(0);
        timer.cleanUp();
      };
    }
  }, [restartIdleTimer, idleTimeoutData, routes, logoutInactivityRoute, logoutRoute, onRouteChange, onStayLoggedIn]);
  return /*#__PURE__*/React__default.default.createElement(react.Modal, {
    "data-testid": "idle-logout-confirmation",
    className: classnames__default.default("".concat(Settings.settings.iotPrefix, "--session-timeout-modal"), className),
    size: "sm",
    closeButtonLabel: mergedI18N.closeButtonLabel,
    open: logoutConfirmationCountdown > 0,
    modalHeading: mergedI18N.sessionTimeoutModalHeading,
    primaryButtonText: mergedI18N.sessionTimeoutModalStayLoggedInButton,
    primaryButtonDisabled: stayLoggedInButtonDisabled,
    secondaryButtonText: mergedI18N.sessionTimeoutModalLogoutButton,
    onSecondarySubmit: /*#__PURE__*/_asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee4() {
      var result;
      return _regeneratorRuntime__default.default.wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            // Disable the "Stay Logged in" button after the "Log out" button is clicked
            setStayLoggedInButtonDisabled(true);
            _context4.next = 3;
            return onRouteChange(suiteHeaderConstants.SUITE_HEADER_ROUTE_TYPES.LOGOUT, logoutRoute);
          case 3:
            result = _context4.sent;
            if (result) {
              window.location.href = logoutRoute;
            }
          case 5:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    })),
    onRequestSubmit: function onRequestSubmit() {
      setLogoutConfirmationCountdown(0);
      setRestartIdleTimer(function (prevRestartIdleTimer) {
        return !prevRestartIdleTimer;
      });
      onStayLoggedIn();
    }
  }, translate(mergedI18N.sessionTimeoutModalBody, [['{countdown}', logoutConfirmationCountdown]]));
};
IdleLogoutConfirmationModal.defaultProps = defaultProps;
IdleLogoutConfirmationModal.propTypes = propTypes;
IdleLogoutConfirmationModal.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "IdleLogoutConfirmationModal",
  "props": {
    "isAdminView": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "If true, include the originIsAdmin query param in the logout URL",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "appId": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Application ID in suite",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "workspaceId": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Workspace ID in suite",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "className": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Add class name to the rendered Modal component",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "idleTimeoutData": {
      "defaultValue": {
        "value": "{\n  timeout: 1800, // 30 minutes\n  countdown: 30, // 30 seconds\n  cookieName: '_user_inactivity_timeout',\n}",
        "computed": false
      },
      "description": "User inactivity timeout data",
      "type": {
        "name": "shape",
        "value": {
          "timeout": {
            "name": "number",
            "description": "User inactivity timeout, in seconds",
            "required": false
          },
          "countdown": {
            "name": "number",
            "description": "Countdown start value, in seconds, for the logout confirmation modal",
            "required": false
          },
          "cookieName": {
            "name": "string",
            "description": "Cookie name for cross-tab support",
            "required": false
          }
        }
      },
      "required": false
    },
    "routes": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "URLs for routes used on this component",
      "type": {
        "name": "shape",
        "value": {
          "logout": {
            "name": "string",
            "description": "Route for the logout redirect page when Log out button is clicked",
            "required": false
          },
          "logoutInactivity": {
            "name": "string",
            "description": "Route for the logout redirect page when user is logged out due to inactivity",
            "required": false
          },
          "domain": {
            "name": "string",
            "description": "Cookie domain for cross-tab support",
            "required": false
          }
        }
      },
      "required": false
    },
    "onRouteChange": {
      "defaultValue": {
        "value": "async () => Promise.resolve(true)",
        "computed": false
      },
      "description": "Function called before any route change. Returns a Promise<Boolean>. False means the redirect will not happen. This function should never throw an error.",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "onStayLoggedIn": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "description": "Custom function that can be provided in case something else needs to be done when the \"Stay logged in\" button is clicked",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  sessionTimeoutModalHeading: 'Session Timeout',\n  sessionTimeoutModalBody: 'You will be logged out due to inactivity in {countdown} seconds.',\n  sessionTimeoutModalLogoutButton: 'Log out',\n  sessionTimeoutModalStayLoggedInButton: 'Stay logged in',\n  closeButtonLabel: 'Close',\n}",
        "computed": false
      },
      "description": "I18N strings",
      "type": {
        "name": "shape",
        "value": {
          "sessionTimeoutModalHeading": {
            "name": "string",
            "required": false
          },
          "sessionTimeoutModalBody": {
            "name": "string",
            "required": false
          },
          "sessionTimeoutModalLogoutButton": {
            "name": "string",
            "required": false
          },
          "sessionTimeoutModalStayLoggedInButton": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    }
  }
};
var IdleLogoutConfirmationModal$1 = IdleLogoutConfirmationModal;

exports.IdleLogoutConfirmationModalI18NPropTypes = IdleLogoutConfirmationModalI18NPropTypes;
exports.IdleLogoutConfirmationModalIdleTimeoutPropTypes = IdleLogoutConfirmationModalIdleTimeoutPropTypes;
exports.IdleLogoutConfirmationModalRoutePropTypes = IdleLogoutConfirmationModalRoutePropTypes;
exports.default = IdleLogoutConfirmationModal$1;
