"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.PINEntryUsage = void 0;
var _native = require("@react-navigation/native");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _reactNative = require("react-native");
var _Button = _interopRequireWildcard(require("../components/buttons/Button"));
var _PINInput = _interopRequireDefault(require("../components/inputs/PINInput"));
var _InfoBox = require("../components/misc/InfoBox");
var _PopupModal = _interopRequireDefault(require("../components/modals/PopupModal"));
var _KeyboardView = _interopRequireDefault(require("../components/views/KeyboardView"));
var _constants = require("../constants");
var _containerApi = require("../container-api");
var _animatedComponents = require("../contexts/animated-components");
var _auth = require("../contexts/auth");
var _store = require("../contexts/reducers/store");
var _store2 = require("../contexts/store");
var _theme = require("../contexts/theme");
var _error = require("../types/error");
var _navigators = require("../types/navigators");
var _crypto = require("../utils/crypto");
var _testable = require("../utils/testable");
var _InlineErrorText = require("../components/inputs/InlineErrorText");
var _ThemedText = require("../components/texts/ThemedText");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
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; }
let PINEntryUsage = exports.PINEntryUsage = /*#__PURE__*/function (PINEntryUsage) {
  PINEntryUsage[PINEntryUsage["PINCheck"] = 0] = "PINCheck";
  PINEntryUsage[PINEntryUsage["WalletUnlock"] = 1] = "WalletUnlock";
  PINEntryUsage[PINEntryUsage["ChangeBiometrics"] = 2] = "ChangeBiometrics";
  return PINEntryUsage;
}({});
const PINEnter = ({
  setAuthenticated,
  usage = PINEntryUsage.WalletUnlock,
  onCancelAuth
}) => {
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const {
    checkWalletPIN,
    getWalletSecret,
    isBiometricsActive,
    disableBiometrics
  } = (0, _auth.useAuth)();
  const [store, dispatch] = (0, _store2.useStore)();
  const [PIN, setPIN] = (0, _react.useState)('');
  const [continueEnabled, setContinueEnabled] = (0, _react.useState)(true);
  const [displayLockoutWarning, setDisplayLockoutWarning] = (0, _react.useState)(false);
  const [biometricsErr, setBiometricsErr] = (0, _react.useState)(false);
  const navigation = (0, _native.useNavigation)();
  const [alertModalVisible, setAlertModalVisible] = (0, _react.useState)(false);
  const [biometricsEnrollmentChange, setBiometricsEnrollmentChange] = (0, _react.useState)(false);
  const {
    ColorPallet,
    TextTheme,
    Assets,
    PINEnterTheme
  } = (0, _theme.useTheme)();
  const {
    ButtonLoading
  } = (0, _animatedComponents.useAnimatedComponents)();
  const [logger, {
    enableHiddenDevModeTrigger,
    attemptLockoutConfig: {
      baseRules,
      thresholdRules
    } = _constants.attemptLockoutConfig
  }] = (0, _containerApi.useServices)([_containerApi.TOKENS.UTIL_LOGGER, _containerApi.TOKENS.CONFIG]);
  const developerOptionCount = (0, _react.useRef)(0);
  const touchCountToEnableBiometrics = 9;
  const [inlineMessageField, setInlineMessageField] = (0, _react.useState)();
  const [inlineMessages] = (0, _containerApi.useServices)([_containerApi.TOKENS.INLINE_ERRORS]);
  const [alertModalMessage, setAlertModalMessage] = (0, _react.useState)('');
  // Temporary until all use cases are built with the new design
  const isNewDesign = usage === PINEntryUsage.ChangeBiometrics;
  const style = _reactNative.StyleSheet.create({
    screenContainer: {
      height: '100%',
      backgroundColor: ColorPallet.brand.primaryBackground,
      padding: 20,
      justifyContent: 'space-between'
    },
    // below used as helpful labels for views, no properties needed atp
    contentContainer: {},
    controlsContainer: {},
    buttonContainer: {
      width: '100%'
    },
    notifyText: {
      ...TextTheme.normal,
      marginVertical: 5
    },
    helpText: {
      alignSelf: 'auto',
      textAlign: 'left',
      marginBottom: isNewDesign ? 40 : 16
    },
    parenthesisText: {
      ...TextTheme.caption
    },
    modalText: {
      marginVertical: 5
    },
    image: {
      ...PINEnterTheme.image,
      height: Assets.img.logoSecondary.height,
      width: Assets.img.logoSecondary.width,
      resizeMode: Assets.img.logoSecondary.resizeMode
    },
    title: {
      marginTop: isNewDesign ? 20 : 0,
      marginBottom: isNewDesign ? 40 : 20
    },
    subTitle: {
      marginBottom: 20
    },
    subText: {
      marginBottom: isNewDesign ? 20 : 4
    }
  });
  const inputLabelText = {
    [PINEntryUsage.ChangeBiometrics]: t('PINEnter.ChangeBiometricsInputLabel'),
    [PINEntryUsage.PINCheck]: t('PINEnter.AppSettingChangedEnterPIN'),
    [PINEntryUsage.WalletUnlock]: t('PINEnter.EnterPIN')
  };
  const inputTestId = {
    [PINEntryUsage.ChangeBiometrics]: 'BiometricChangedEnterPIN',
    [PINEntryUsage.PINCheck]: 'AppSettingChangedEnterPIN',
    [PINEntryUsage.WalletUnlock]: 'EnterPIN'
  };
  const primaryButtonText = {
    [PINEntryUsage.ChangeBiometrics]: t('Global.Continue'),
    [PINEntryUsage.PINCheck]: t('PINEnter.AppSettingSave'),
    [PINEntryUsage.WalletUnlock]: t('PINEnter.Unlock')
  };
  const primaryButtonTestId = {
    [PINEntryUsage.ChangeBiometrics]: 'Continue',
    [PINEntryUsage.PINCheck]: 'AppSettingSave',
    [PINEntryUsage.WalletUnlock]: 'Enter'
  };
  const incrementDeveloperMenuCounter = (0, _react.useCallback)(() => {
    if (developerOptionCount.current >= touchCountToEnableBiometrics) {
      developerOptionCount.current = 0;
      dispatch({
        type: _store.DispatchAction.ENABLE_DEVELOPER_MODE,
        payload: [true]
      });
      navigation.navigate(_navigators.Screens.Developer);
      return;
    }
    developerOptionCount.current = developerOptionCount.current + 1;
  }, [dispatch, navigation]);
  const gotoPostAuthScreens = (0, _react.useCallback)(() => {
    if (store.onboarding.postAuthScreens.length) {
      const screen = store.onboarding.postAuthScreens[0];
      if (screen) {
        navigation.navigate(screen);
      }
    }
  }, [store.onboarding.postAuthScreens, navigation]);
  const isContinueDisabled = () => {
    if (inlineMessages.enabled) {
      return !continueEnabled;
    }
    return !continueEnabled || PIN.length < _constants.minPINLength;
  };

  // listen for biometrics error event
  (0, _react.useEffect)(() => {
    const handle = _reactNative.DeviceEventEmitter.addListener(_constants.EventTypes.BIOMETRY_ERROR, value => {
      setBiometricsErr(prev => value ?? !prev);
    });
    return () => {
      handle.remove();
    };
  }, []);

  // This method is used to notify the app that the user is able to receive
  // another lockout penalty
  const unMarkServedPenalty = (0, _react.useCallback)(() => {
    dispatch({
      type: _store.DispatchAction.ATTEMPT_UPDATED,
      payload: [{
        loginAttempts: store.loginAttempt.loginAttempts,
        lockoutDate: undefined,
        servedPenalty: undefined
      }]
    });
  }, [dispatch, store.loginAttempt.loginAttempts]);
  const attemptLockout = (0, _react.useCallback)(async penalty => {
    // set the attempt lockout time
    dispatch({
      type: _store.DispatchAction.ATTEMPT_UPDATED,
      payload: [{
        loginAttempts: store.loginAttempt.loginAttempts + 1,
        lockoutDate: Date.now() + penalty,
        servedPenalty: false
      }]
    });
  }, [dispatch, store.loginAttempt.loginAttempts]);
  const getLockoutPenalty = (0, _react.useCallback)(attempts => {
    let penalty = baseRules[attempts];
    if (!penalty && attempts >= thresholdRules.threshold && !(attempts % thresholdRules.increment)) {
      penalty = thresholdRules.thresholdPenaltyDuration;
    }
    return penalty;
  }, [baseRules, thresholdRules]);
  const loadWalletCredentials = (0, _react.useCallback)(async () => {
    if (usage === PINEntryUsage.PINCheck || usage === PINEntryUsage.ChangeBiometrics) {
      return;
    }
    const walletSecret = await getWalletSecret();
    if (walletSecret) {
      // remove lockout notification
      dispatch({
        type: _store.DispatchAction.LOCKOUT_UPDATED,
        payload: [{
          displayNotification: false
        }]
      });

      // reset login attempts if login is successful
      dispatch({
        type: _store.DispatchAction.ATTEMPT_UPDATED,
        payload: [{
          loginAttempts: 0
        }]
      });
      setAuthenticated(true);
      gotoPostAuthScreens();
    }
  }, [usage, getWalletSecret, dispatch, setAuthenticated, gotoPostAuthScreens]);
  (0, _react.useEffect)(() => {
    const handle = _reactNative.InteractionManager.runAfterInteractions(async () => {
      if (!store.preferences.useBiometry) {
        return;
      }
      try {
        const active = await isBiometricsActive();
        if (!active) {
          // biometry state has changed, display message and disable biometry
          setBiometricsEnrollmentChange(true);
          await disableBiometrics();
          dispatch({
            type: _store.DispatchAction.USE_BIOMETRY,
            payload: [false]
          });
        }
        await loadWalletCredentials();
      } catch (error) {
        logger.error(`error checking biometrics / loading credentials: ${JSON.stringify(error)}`);
      }
    });
    return handle.cancel;
  }, [store.preferences.useBiometry, isBiometricsActive, disableBiometrics, dispatch, loadWalletCredentials, logger]);
  (0, _react.useEffect)(() => {
    // check number of login attempts and determine if app should apply lockout
    const attempts = store.loginAttempt.loginAttempts;
    // display warning if we are one away from a lockout
    const displayWarning = !!getLockoutPenalty(attempts + 1);
    setDisplayLockoutWarning(displayWarning);
  }, [store.loginAttempt.loginAttempts, getLockoutPenalty]);
  (0, _react.useEffect)(() => {
    setInlineMessageField(undefined);
  }, [PIN]);
  const unlockWalletWithPIN = (0, _react.useCallback)(async PIN => {
    try {
      setContinueEnabled(false);
      const result = await checkWalletPIN(PIN);
      if (store.loginAttempt.servedPenalty) {
        // once the user starts entering their PIN, unMark them as having served their
        // lockout penalty
        unMarkServedPenalty();
      }
      if (!result) {
        const newAttempt = store.loginAttempt.loginAttempts + 1;
        const attemptsLeft = (thresholdRules.increment - newAttempt % thresholdRules.increment) % thresholdRules.increment;
        if (!inlineMessages.enabled && !getLockoutPenalty(newAttempt)) {
          // skip displaying modals if we are going to lockout
          setAlertModalVisible(true);
        }
        if (attemptsLeft > 1) {
          if (inlineMessages.enabled) {
            setInlineMessageField({
              message: t('PINEnter.IncorrectPINTries', {
                tries: attemptsLeft
              }),
              // Example: 'Incorrect PIN: 4 tries before timeout'
              inlineType: _InlineErrorText.InlineErrorType.error,
              config: inlineMessages
            });
          } else {
            setAlertModalMessage(t('PINEnter.IncorrectPINTries', {
              tries: attemptsLeft
            }));
          }
        } else if (attemptsLeft === 1) {
          if (inlineMessages.enabled) {
            setInlineMessageField({
              message: t('PINEnter.LastTryBeforeTimeout'),
              // Show last try warning
              inlineType: _InlineErrorText.InlineErrorType.error,
              config: inlineMessages
            });
          } else {
            setAlertModalMessage(t('PINEnter.LastTryBeforeTimeout'));
          }
        } else {
          const penalty = getLockoutPenalty(newAttempt);
          if (penalty !== undefined) {
            attemptLockout(penalty); // Only call attemptLockout if penalty is defined
          }
          return;
        }
        setContinueEnabled(true);

        // log incorrect login attempts
        dispatch({
          type: _store.DispatchAction.ATTEMPT_UPDATED,
          payload: [{
            loginAttempts: newAttempt
          }]
        });
        return;
      }

      // reset login attempts if login is successful
      dispatch({
        type: _store.DispatchAction.ATTEMPT_UPDATED,
        payload: [{
          loginAttempts: 0
        }]
      });

      // remove lockout notification if login is successful
      dispatch({
        type: _store.DispatchAction.LOCKOUT_UPDATED,
        payload: [{
          displayNotification: false
        }]
      });
      setAuthenticated(true);
      gotoPostAuthScreens();
    } catch (err) {
      const error = new _error.BifoldError(t('Error.Title1041'), t('Error.Message1041'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1041);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
    }
  }, [checkWalletPIN, store.loginAttempt, unMarkServedPenalty, getLockoutPenalty, dispatch, setAuthenticated, gotoPostAuthScreens, t, attemptLockout, inlineMessages, thresholdRules.increment]);
  const clearAlertModal = (0, _react.useCallback)(() => {
    switch (usage) {
      case PINEntryUsage.PINCheck:
        setAlertModalVisible(false);
        setAuthenticated(false);
        break;
      case PINEntryUsage.ChangeBiometrics:
        setAlertModalVisible(false);
        setAuthenticated(false);
        break;
      default:
        setAlertModalVisible(false);
        break;
    }
    setAlertModalVisible(false);
  }, [usage, setAuthenticated]);
  const verifyPIN = (0, _react.useCallback)(async PIN => {
    try {
      const walletSecret = await getWalletSecret();
      if (!walletSecret) {
        throw new Error('Wallet secret not found');
      }
      const key = await (0, _crypto.hashPIN)(PIN, walletSecret.salt);
      if (walletSecret.key !== key) {
        setAlertModalVisible(true);
        return;
      }
      setAuthenticated(true);
    } catch (err) {
      const error = new _error.BifoldError(t('Error.Title1042'), t('Error.Message1042'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1042);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
    }
  }, [getWalletSecret, setAuthenticated, t]);

  // both of the async functions called in this function are completely wrapped in try catch
  const onPINInputCompleted = (0, _react.useCallback)(async PIN => {
    if (inlineMessages.enabled && PIN.length < _constants.minPINLength) {
      setInlineMessageField({
        message: t('PINCreate.PINTooShort'),
        inlineType: _InlineErrorText.InlineErrorType.error,
        config: inlineMessages
      });
      return;
    }
    setContinueEnabled(false);
    if (usage === PINEntryUsage.PINCheck || usage === PINEntryUsage.ChangeBiometrics) {
      await verifyPIN(PIN);
    }
    if (usage === PINEntryUsage.WalletUnlock) {
      await unlockWalletWithPIN(PIN);
    }
  }, [usage, verifyPIN, unlockWalletWithPIN, t, inlineMessages]);
  const displayHelpText = (0, _react.useCallback)(() => {
    if (store.lockout.displayNotification) {
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        style: style.helpText
      }, t('PINEnter.LockedOut', {
        time: String(store.preferences.autoLockTime ?? _constants.defaultAutoLockTime)
      })), /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        style: style.helpText
      }, t('PINEnter.ReEnterPIN')));
    }
    if (biometricsEnrollmentChange) {
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        style: style.helpText
      }, t('PINEnter.BiometricsChanged')), /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        style: style.helpText
      }, t('PINEnter.BiometricsChangedEnterPIN')));
    }
    if (biometricsErr) {
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        style: style.helpText
      }, t('PINEnter.BiometricsError')), /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        style: style.helpText
      }, t('PINEnter.BiometricsErrorEnterPIN')));
    }
    if (usage === PINEntryUsage.PINCheck) {
      return /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        style: style.helpText
      }, t('PINEnter.AppSettingChanged'));
    }
    if (usage === PINEntryUsage.ChangeBiometrics) {
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        variant: "headingTwo",
        style: style.title
      }, t('PINEnter.ChangeBiometricsHeader')), /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
        style: style.helpText
      }, t('PINEnter.ChangeBiometricsSubtext')));
    }
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
      variant: "headingTwo",
      style: style.title
    }, t('PINEnter.Title')), /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
      variant: "labelSubtitle",
      style: style.subTitle
    }, t('PINEnter.SubText')));
  }, [store.lockout.displayNotification, style.helpText, t, biometricsEnrollmentChange, biometricsErr, style.title, style.subTitle, store.preferences.autoLockTime, usage]);
  return /*#__PURE__*/_react.default.createElement(_KeyboardView.default, null, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: style.screenContainer
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: style.contentContainer
  }, usage === PINEntryUsage.WalletUnlock && enableHiddenDevModeTrigger ? /*#__PURE__*/_react.default.createElement(_reactNative.Pressable, {
    onPress: incrementDeveloperMenuCounter,
    testID: (0, _testable.testIdWithKey)('DeveloperCounter')
  }, displayHelpText()) : displayHelpText(), /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
    variant: "bold",
    style: style.subText
  }, inputLabelText[usage], usage === PINEntryUsage.ChangeBiometrics && /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
    style: style.parenthesisText
  }, ' ', t('PINEnter.ChangeBiometricsInputLabelParenthesis'))), /*#__PURE__*/_react.default.createElement(_PINInput.default, {
    onPINChanged: p => {
      setPIN(p);
      if (p.length === _constants.minPINLength) {
        _reactNative.Keyboard.dismiss();
      }
    },
    testID: (0, _testable.testIdWithKey)(inputTestId[usage]),
    accessibilityLabel: inputLabelText[usage],
    autoFocus: true,
    inlineMessage: inlineMessageField
  })), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: style.controlsContainer
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: style.buttonContainer
  }, /*#__PURE__*/_react.default.createElement(_Button.default, {
    title: primaryButtonText[usage],
    buttonType: _Button.ButtonType.Primary,
    testID: (0, _testable.testIdWithKey)(primaryButtonTestId[usage]),
    disabled: isContinueDisabled(),
    accessibilityLabel: primaryButtonText[usage],
    onPress: () => {
      _reactNative.Keyboard.dismiss();
      onPINInputCompleted(PIN);
    }
  }, !continueEnabled && /*#__PURE__*/_react.default.createElement(ButtonLoading, null))), store.preferences.useBiometry && usage === PINEntryUsage.WalletUnlock && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
    style: {
      alignSelf: 'center',
      marginTop: 10
    }
  }, t('PINEnter.Or')), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: [style.buttonContainer, {
      marginTop: 10
    }]
  }, /*#__PURE__*/_react.default.createElement(_Button.default, {
    title: t('PINEnter.BiometricsUnlock'),
    buttonType: _Button.ButtonType.Secondary,
    testID: (0, _testable.testIdWithKey)('BiometricsUnlock'),
    disabled: !continueEnabled,
    accessibilityLabel: t('PINEnter.BiometricsUnlock'),
    onPress: loadWalletCredentials
  }))), usage === PINEntryUsage.PINCheck && /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: [style.buttonContainer, {
      marginTop: 10
    }]
  }, /*#__PURE__*/_react.default.createElement(_Button.default, {
    title: t('PINEnter.AppSettingCancel'),
    buttonType: _Button.ButtonType.Secondary,
    testID: (0, _testable.testIdWithKey)('AppSettingCancel'),
    accessibilityLabel: t('PINEnter.AppSettingCancel'),
    onPress: () => onCancelAuth === null || onCancelAuth === void 0 ? void 0 : onCancelAuth(false)
  })))), alertModalVisible && /*#__PURE__*/_react.default.createElement(_PopupModal.default, {
    notificationType: _InfoBox.InfoBoxType.Info,
    title: t('PINEnter.IncorrectPIN'),
    bodyContent: /*#__PURE__*/_react.default.createElement(_reactNative.View, null, /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
      variant: "popupModalText",
      style: style.modalText
    }, alertModalMessage), displayLockoutWarning ? /*#__PURE__*/_react.default.createElement(_ThemedText.ThemedText, {
      variant: "popupModalText",
      style: style.modalText
    }, t('PINEnter.AttemptLockoutWarning')) : null),
    onCallToActionLabel: t('Global.Okay'),
    onCallToActionPressed: clearAlertModal
  }));
};
var _default = exports.default = PINEnter;
//# sourceMappingURL=PINEnter.js.map