"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _native = require("@react-navigation/native");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _reactNative = require("react-native");
var _ButtonApi = require("../components/buttons/Button-api");
var _PINInput = _interopRequireDefault(require("../components/inputs/PINInput"));
var _PINValidationHelper = _interopRequireDefault(require("../components/misc/PINValidationHelper"));
var _AlertModal = _interopRequireDefault(require("../components/modals/AlertModal"));
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/store");
var _theme = require("../contexts/theme");
var _usePINValidation = require("../hooks/usePINValidation");
var _types = require("../modules/history/types");
var _error = require("../types/error");
var _navigators = require("../types/navigators");
var _agent = require("../utils/agent");
var _testable = require("../utils/testable");
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; }
// eslint-disable-next-line import/no-named-as-default

const PINChange = () => {
  const {
    agent
  } = (0, _agent.useAppAgent)();
  const {
    checkWalletPIN,
    rekeyWallet
  } = (0, _auth.useAuth)();
  const [PIN, setPIN] = (0, _react.useState)('');
  const [PINTwo, setPINTwo] = (0, _react.useState)('');
  const [PINOld, setPINOld] = (0, _react.useState)('');
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const navigation = (0, _native.useNavigation)();
  const [store] = (0, _store.useStore)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const {
    ColorPallet
  } = (0, _theme.useTheme)();
  const {
    ButtonLoading
  } = (0, _animatedComponents.useAnimatedComponents)();
  const PINTwoInputRef = (0, _react.useRef)(null);
  const createPINButtonRef = (0, _react.useRef)(null);
  const [PINHeader, Button, inlineMessages, logger, historyManagerCurried, historyEnabled, historyEventsLogger] = (0, _containerApi.useServices)([_containerApi.TOKENS.COMPONENT_PIN_HEADER, _containerApi.TOKENS.COMP_BUTTON, _containerApi.TOKENS.INLINE_ERRORS, _containerApi.TOKENS.UTIL_LOGGER, _containerApi.TOKENS.FN_LOAD_HISTORY, _containerApi.TOKENS.HISTORY_ENABLED, _containerApi.TOKENS.HISTORY_EVENTS_LOGGER]);
  const {
    PINValidations,
    validatePINEntry,
    inlineMessageField1,
    inlineMessageField2,
    modalState,
    setModalState,
    clearModal,
    PINSecurity
  } = (0, _usePINValidation.usePINValidation)(PIN, PINTwo);
  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: {}
  });
  const checkOldPIN = (0, _react.useCallback)(async PIN => {
    const valid = await checkWalletPIN(PIN);
    if (!valid) {
      setModalState({
        visible: true,
        title: t('PINCreate.InvalidPIN'),
        message: t(`PINCreate.Message.OldPINIncorrect`),
        onModalDismiss: clearModal
      });
    }
    return valid;
  }, [checkWalletPIN, t, setModalState, clearModal]);
  const logHistoryRecord = (0, _react.useCallback)(() => {
    try {
      if (!(agent && historyEnabled)) {
        logger.trace(`[${PINChange.name}]:[logHistoryRecord] Skipping history log, either history function disabled or agent undefined`);
        return;
      }
      const historyManager = historyManagerCurried(agent);
      /** Save history record for pin edited */
      const recordData = {
        type: _types.HistoryCardType.PinChanged,
        message: _types.HistoryCardType.PinChanged,
        createdAt: new Date()
      };
      historyManager.saveHistory(recordData);
    } catch (err) {
      logger.error(`[${PINChange.name}]:[logHistoryRecord] Error saving history: ${err}`);
    }
  }, [agent, historyEnabled, logger, historyManagerCurried]);
  const handleChangePinTap = async () => {
    try {
      setIsLoading(true);
      const valid = validatePINEntry(PIN, PINTwo);
      if (valid) {
        const oldPinValid = await checkOldPIN(PINOld);
        if (oldPinValid) {
          const success = await rekeyWallet(agent, PINOld, PIN, store.preferences.useBiometry);
          if (success) {
            if (historyEventsLogger.logPinChanged) {
              logHistoryRecord();
            }
            setModalState({
              visible: true,
              title: t('PINChange.PinChangeSuccessTitle'),
              message: t('PINChange.PinChangeSuccessMessage'),
              onModalDismiss: () => {
                navigation.navigate(_navigators.Screens.Settings);
                clearModal();
              }
            });
          }
        }
      }
    } catch (err) {
      const error = new _error.BifoldError(t('Error.Title1049'), t('Error.Message1049'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1049);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.ERROR_ADDED, error);
    } finally {
      setIsLoading(false);
    }
  };
  const isContinueDisabled = (0, _react.useMemo)(() => {
    if (inlineMessages || isLoading) {
      return false;
    }
    return PIN === '' || PINTwo === '' || PINOld === '' || PIN.length < _constants.minPINLength || PINTwo.length < _constants.minPINLength;
  }, [inlineMessages, isLoading, PIN, PINTwo, PINOld]);
  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
  }, /*#__PURE__*/_react.default.createElement(PINHeader, {
    updatePin: true
  }), /*#__PURE__*/_react.default.createElement(_PINInput.default, {
    label: t('PINChange.EnterOldPINTitle'),
    testID: (0, _testable.testIdWithKey)('EnterOldPIN'),
    accessibilityLabel: t('PINChange.EnterOldPIN'),
    onPINChanged: p => {
      setPINOld(p);
    }
  }), /*#__PURE__*/_react.default.createElement(_PINInput.default, {
    label: t('PINChange.EnterPINTitle'),
    onPINChanged: p => {
      setPIN(p);
      if (p.length === _constants.minPINLength && PINTwoInputRef !== null && PINTwoInputRef !== void 0 && PINTwoInputRef.current) {
        PINTwoInputRef.current.focus();
        const reactTag = (0, _reactNative.findNodeHandle)(PINTwoInputRef.current);
        if (reactTag) {
          _reactNative.AccessibilityInfo.setAccessibilityFocus(reactTag);
        }
      }
    },
    testID: (0, _testable.testIdWithKey)('EnterPIN'),
    accessibilityLabel: t('PINCreate.EnterPIN'),
    autoFocus: false,
    inlineMessage: inlineMessageField1
  }), /*#__PURE__*/_react.default.createElement(_PINInput.default, {
    label: t('PINChange.ReenterPIN'),
    onPINChanged: p => {
      setPINTwo(p);
      if (p.length === _constants.minPINLength) {
        _reactNative.Keyboard.dismiss();
        const reactTag = (createPINButtonRef === null || createPINButtonRef === void 0 ? void 0 : createPINButtonRef.current) && (0, _reactNative.findNodeHandle)(createPINButtonRef.current);
        if (reactTag) {
          _reactNative.AccessibilityInfo.setAccessibilityFocus(reactTag);
        }
      }
    },
    testID: (0, _testable.testIdWithKey)('ReenterPIN'),
    accessibilityLabel: t('PINChange.ReenterPIN'),
    autoFocus: false,
    ref: PINTwoInputRef,
    inlineMessage: inlineMessageField2
  }), PINSecurity.displayHelper && /*#__PURE__*/_react.default.createElement(_PINValidationHelper.default, {
    validations: PINValidations
  }), modalState.visible && /*#__PURE__*/_react.default.createElement(_AlertModal.default, {
    title: modalState.title,
    message: modalState.message,
    submit: modalState.onModalDismiss
  })), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: style.controlsContainer
  }, /*#__PURE__*/_react.default.createElement(Button, {
    title: t('PINChange.ChangePIN'),
    testID: (0, _testable.testIdWithKey)('ChangePIN'),
    accessibilityLabel: t('PINChange.ChangePIN'),
    buttonType: _ButtonApi.ButtonType.Primary,
    disabled: isContinueDisabled,
    onPress: handleChangePinTap,
    ref: createPINButtonRef
  }, isLoading ? /*#__PURE__*/_react.default.createElement(ButtonLoading, null) : null))));
};
var _default = exports.default = PINChange;
//# sourceMappingURL=PINChange.js.map