"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useActivity = exports.AutoLockTime = exports.ActivityProvider = exports.ActivityContext = void 0;
var _reactHooks = require("@credo-ts/react-hooks");
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _auth = require("./auth");
var _store = require("./store");
var _store2 = require("./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() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, 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 ActivityContext = exports.ActivityContext = /*#__PURE__*/(0, _react.createContext)(null);
const ActivityProvider = ({
  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 lastActiveTimeRef = (0, _react.useRef)(undefined);
  const timeoutInMilliseconds = (0, _react.useRef)((store.preferences.autoLockTime ?? _constants.defaultAutoLockTime) * 60000);
  const inactivityTimeoutRef = (0, _react.useRef)(null);
  const prevAppStateStatusRef = (0, _react.useRef)(_reactNative.AppState.currentState);
  const [appStateStatus, setAppStateStatus] = (0, _react.useState)(_reactNative.AppState.currentState);
  const panResponder = (0, _react.useRef)(_reactNative.PanResponder.create({
    onStartShouldSetPanResponderCapture: () => {
      // some user interaction detected, reset timeout
      resetInactivityTimeout(timeoutInMilliseconds.current);

      // returns false so the PanResponder doesn't consume the touch event
      return false;
    }
  })).current;
  const lockOutUser = (0, _react.useCallback)(async () => {
    if (!store.authentication.didAuthenticate) {
      return;
    }
    try {
      removeSavedWalletSecret();
      await (agent === null || agent === void 0 ? void 0 : agent.shutdown());
      logger.info('Agent shutdown successfully');
    } catch (error) {
      logger.error(`Error during agent shutdown: ${error}`);
    }
    dispatch({
      type: _store2.DispatchAction.DID_AUTHENTICATE,
      payload: [false]
    });
    dispatch({
      type: _store2.DispatchAction.LOCKOUT_UPDATED,
      payload: [{
        displayNotification: true
      }]
    });
  }, [agent, removeSavedWalletSecret, dispatch, logger, store.authentication.didAuthenticate]);
  const clearInactivityTimeoutIfExists = (0, _react.useCallback)(() => {
    if (inactivityTimeoutRef.current) {
      clearTimeout(inactivityTimeoutRef.current);
    }
  }, []);
  const resetInactivityTimeout = (0, _react.useCallback)(async milliseconds => {
    clearInactivityTimeoutIfExists();
    lastActiveTimeRef.current = Date.now();

    // do not set timeout if timeout duration is set to 0
    if (milliseconds > 0) {
      // create new timeout
      inactivityTimeoutRef.current = setTimeout(async () => {
        await lockOutUser();
      }, milliseconds);
    }
  }, [clearInactivityTimeoutIfExists, lockOutUser]);
  (0, _react.useEffect)(() => {
    // listener for backgrounding / foregrounding
    const eventSubscription = _reactNative.AppState.addEventListener('change', async nextAppState => {
      // if going into the background
      if (['active', 'inactive'].includes(prevAppStateStatusRef.current) && nextAppState === 'background') {
        // remove timeout when backgrounded as timeout refs can be lost when app is backgrounded
        clearInactivityTimeoutIfExists();

        // if going to background after agent initialization, stop message pickup
        if (agent !== null && agent !== void 0 && agent.isInitialized) {
          try {
            await agent.mediationRecipient.stopMessagePickup();
            logger.info('Stopped agent message pickup');
          } catch (err) {
            logger.error(`Error stopping agent message pickup, ${err}`);
          }
        }
      }

      // if coming to the foreground
      if (prevAppStateStatusRef.current === 'background' && ['active', 'inactive'].includes(nextAppState)) {
        // if app was in background for longer than allowed time, lock out user
        if (lastActiveTimeRef.current && Date.now() - lastActiveTimeRef.current >= timeoutInMilliseconds.current && timeoutInMilliseconds.current > 0) {
          await lockOutUser();
        } else if (agent !== null && agent !== void 0 && agent.isInitialized) {
          // otherwise if agent is initialized, restart message pickup
          try {
            await agent.mediationRecipient.initiateMessagePickup();
            logger.info('Restarted agent message pickup');
          } catch (err) {
            logger.error(`Error restarting agent message pickup, ${err}`);
          }
        }

        // app coming into the foreground is 'user activity', reset timeout
        await resetInactivityTimeout(timeoutInMilliseconds.current);
      }
      prevAppStateStatusRef.current = nextAppState;
      setAppStateStatus(nextAppState);
    });

    // initial timeout setup
    resetInactivityTimeout(timeoutInMilliseconds.current);
    return () => {
      clearInactivityTimeoutIfExists();
      eventSubscription.remove();
    };
  }, [clearInactivityTimeoutIfExists, lockOutUser, resetInactivityTimeout, timeoutInMilliseconds, agent, logger]);
  (0, _react.useEffect)(() => {
    // user has updated settings for auto lock time
    timeoutInMilliseconds.current = store.preferences.autoLockTime * 60000;
  }, [store.preferences.autoLockTime]);
  return /*#__PURE__*/_react.default.createElement(ActivityContext.Provider, {
    value: {
      appStateStatus
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, _extends({
    style: {
      flex: 1
    }
  }, panResponder.panHandlers), children));
};
exports.ActivityProvider = ActivityProvider;
const useActivity = () => (0, _react.useContext)(ActivityContext);
exports.useActivity = useActivity;
//# sourceMappingURL=activity.js.map