"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.AutoLockTime = void 0;
var _reactHooks = require("@credo-ts/react-hooks");
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _auth = require("../../contexts/auth");
var _store = require("../../contexts/store");
var _store2 = require("../../contexts/reducers/store");
var _containerApi = require("../../container-api");
var _constants = require("../../constants");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
// number of minutes before the timeout action is triggered
// a value of 0 will never trigger the lock out  action and an undefined value will default to 5 minutes
const AutoLockTime = exports.AutoLockTime = {
  OneMinute: 1,
  ThreeMinutes: 3,
  FiveMinutes: 5,
  Never: 0
};
const InactivityWrapper = ({
  children
}) => {
  const [logger] = (0, _containerApi.useServices)([_containerApi.TOKENS.UTIL_LOGGER]);
  const [store, dispatch] = (0, _store.useStore)();
  const {
    agent
  } = (0, _reactHooks.useAgent)();
  const {
    removeSavedWalletSecret
  } = (0, _auth.useAuth)();
  const timer = (0, _react.useRef)(undefined);
  const timeoutAsMilliseconds = (0, _react.useRef)((store.preferences.autoLockTime ?? _constants.defaultAutoLockTime) * 60000);
  const inactivityTimer = (0, _react.useRef)(null);
  const panResponder = _react.default.useRef(_reactNative.PanResponder.create({
    onStartShouldSetPanResponderCapture: () => {
      // some user interaction detected, reset timeout
      resetInactivityTimeout(timeoutAsMilliseconds.current);

      // returns false so the PanResponder doesn't consume the touch event
      return false;
    }
  })).current;
  const lockUserOut = (0, _react.useCallback)(async () => {
    // FIXME: need to ignore if the user isn't logged in
    try {
      removeSavedWalletSecret();
      await (agent === null || agent === void 0 ? void 0 : agent.wallet.close());
    } catch (error) {
      logger.error(`Error closing agent wallet, ${error}`);
    }
    dispatch({
      type: _store2.DispatchAction.DID_AUTHENTICATE,
      payload: [{
        didAuthenticate: false
      }]
    });
    dispatch({
      type: _store2.DispatchAction.LOCKOUT_UPDATED,
      payload: [{
        displayNotification: true
      }]
    });
  }, [agent, removeSavedWalletSecret, dispatch, logger]);
  const clearTimer = (0, _react.useCallback)(() => {
    if (inactivityTimer.current) {
      clearTimeout(inactivityTimer.current);
    }
  }, []);
  const resetInactivityTimeout = (0, _react.useCallback)(milliseconds => {
    // remove existing timeout
    clearTimer();
    timer.current = Date.now();

    // do not start timer if timeout is set to 0
    if (milliseconds > 0) {
      // create new timeout
      inactivityTimer.current = setTimeout(async () => {
        lockUserOut();
      }, milliseconds);
    }
  }, [clearTimer, lockUserOut]);
  (0, _react.useEffect)(() => {
    // Setup listener for app state changes (background/ foreground movement)
    const eventSubscription = _reactNative.AppState.addEventListener('change', nextAppState => {
      if (_reactNative.AppState.currentState === 'active' && ['inactive', 'background'].includes(nextAppState)) {
        if (nextAppState === 'inactive') {
          // special case for iOS devices when a prompt is shown
          return;
        }

        // remove timer
        clearTimer();
      }
      if (_reactNative.AppState.currentState === 'active' && ['active'].includes(nextAppState)) {
        if (nextAppState === 'inactive') {
          // special case for iOS devices when a prompt is shown
          return;
        }
        if (timer.current) {
          if (Date.now() - timer.current >= timeoutAsMilliseconds.current && timeoutAsMilliseconds.current > 0) {
            // app has been in the background/ inactive for longer than the timeout set, lock user out
            lockUserOut();
          }
        }

        // app coming into the foreground is 'user activity', restart timer
        resetInactivityTimeout(timeoutAsMilliseconds.current);
      }
    });

    // initiate inactivity timer
    resetInactivityTimeout(timeoutAsMilliseconds.current);
    return () => {
      // clean up timer and event listener when component unmounts
      clearTimer();
      eventSubscription.remove();
    };
  }, [clearTimer, lockUserOut, resetInactivityTimeout, timeoutAsMilliseconds]);
  (0, _react.useEffect)(() => {
    // user has updated settings for auto lock time
    timeoutAsMilliseconds.current = store.preferences.autoLockTime * 60000;
  }, [store.preferences.autoLockTime]);
  return /*#__PURE__*/_react.default.createElement(_reactNative.View, _extends({
    style: {
      flex: 1
    }
  }, panResponder.panHandlers), children);
};
var _default = exports.default = InactivityWrapper;
//# sourceMappingURL=InactivityWrapper.js.map