"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _elements = require("@react-navigation/elements");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _BiometryControl = _interopRequireDefault(require("../components/inputs/BiometryControl"));
var _SafeAreaModal = _interopRequireDefault(require("../components/modals/SafeAreaModal"));
var _containerApi = require("../container-api");
var _auth = require("../contexts/auth");
var _store = require("../contexts/reducers/store");
var _store2 = require("../contexts/store");
var _theme = require("../contexts/theme");
var _types = require("../modules/history/types");
var _agent = require("../utils/agent");
var _PINEnter = _interopRequireWildcard(require("./PINEnter"));
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; }
const BackButton = ({
  setCanSeeCheckPIN
}) => /*#__PURE__*/_react.default.createElement(_elements.HeaderBackButton, {
  onPress: () => setCanSeeCheckPIN(false),
  tintColor: "white",
  labelVisible: false
});
const ToggleBiometry = () => {
  const [store, dispatch] = (0, _store2.useStore)();
  const {
    agent
  } = (0, _agent.useAppAgent)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const [logger, historyManagerCurried, historyEnabled, historyEventsLogger] = (0, _containerApi.useServices)([_containerApi.TOKENS.UTIL_LOGGER, _containerApi.TOKENS.FN_LOAD_HISTORY, _containerApi.TOKENS.HISTORY_ENABLED, _containerApi.TOKENS.HISTORY_EVENTS_LOGGER]);
  const {
    commitWalletToKeychain,
    disableBiometrics
  } = (0, _auth.useAuth)();
  const [biometryEnabled, setBiometryEnabled] = (0, _react.useState)(store.preferences.useBiometry);
  const [canSeeCheckPIN, setCanSeeCheckPIN] = (0, _react.useState)(false);
  const {
    TextTheme,
    ColorPallet
  } = (0, _theme.useTheme)();
  const headerHeight = (0, _elements.useHeaderHeight)();
  const logHistoryRecord = (0, _react.useCallback)(type => {
    try {
      if (!(agent && historyEnabled)) {
        logger.trace(`[${ToggleBiometry.name}]:[logHistoryRecord] Skipping history log, either history function disabled or agent undefined!`);
        return;
      }
      const historyManager = historyManagerCurried(agent);

      /** Save history record for card accepted */
      const recordData = {
        type: type,
        message: type,
        createdAt: new Date()
      };
      historyManager.saveHistory(recordData);
    } catch (err) {
      logger.error(`[${ToggleBiometry.name}]:[logHistoryRecord] Error saving history: ${err}`);
    }
  }, [agent, historyEnabled, logger, historyManagerCurried]);
  const onSwitchToggleAllowed = (0, _react.useCallback)(() => {
    setCanSeeCheckPIN(true);
    if (historyEventsLogger.logToggleBiometry && store.onboarding.didAgreeToTerms && store.onboarding.didConsiderBiometry) {
      const type = _types.HistoryCardType.ActivateBiometry;
      logHistoryRecord(type);
    }
  }, [historyEventsLogger.logToggleBiometry, logHistoryRecord, store.onboarding.didAgreeToTerms, store.onboarding.didConsiderBiometry]);
  const handleBiometryToggle = (0, _react.useCallback)(newValue => {
    if (newValue === biometryEnabled) return;
    onSwitchToggleAllowed();
  }, [biometryEnabled, onSwitchToggleAllowed]);
  const onAuthenticationComplete = (0, _react.useCallback)(status => {
    // If successfully authenticated the toggle may proceed.
    if (status) {
      const newValue = !biometryEnabled;
      setBiometryEnabled(newValue);
      if (newValue) {
        commitWalletToKeychain(newValue).then(() => {
          dispatch({
            type: _store.DispatchAction.USE_BIOMETRY,
            payload: [newValue]
          });
        });
      } else {
        disableBiometrics().then(() => {
          dispatch({
            type: _store.DispatchAction.USE_BIOMETRY,
            payload: [newValue]
          });
        });
      }
      if (historyEventsLogger.logToggleBiometry && store.onboarding.didAgreeToTerms && store.onboarding.didConsiderBiometry) {
        const type = _types.HistoryCardType.DeactivateBiometry;
        logHistoryRecord(type);
      }
    }
    setCanSeeCheckPIN(false);
  }, [biometryEnabled, commitWalletToKeychain, disableBiometrics, dispatch, historyEventsLogger.logToggleBiometry, logHistoryRecord, store.onboarding.didAgreeToTerms, store.onboarding.didConsiderBiometry]);
  const renderHeaderLeft = (0, _react.useCallback)(() => /*#__PURE__*/_react.default.createElement(BackButton, {
    setCanSeeCheckPIN: () => setCanSeeCheckPIN(false)
  }), [setCanSeeCheckPIN]);
  return /*#__PURE__*/_react.default.createElement(_BiometryControl.default, {
    biometryEnabled: biometryEnabled,
    onBiometryToggle: handleBiometryToggle
  }, /*#__PURE__*/_react.default.createElement(_SafeAreaModal.default, {
    style: {
      backgroundColor: ColorPallet.brand.primaryBackground
    },
    visible: canSeeCheckPIN,
    transparent: false,
    animationType: 'slide',
    presentationStyle: "fullScreen"
  }, /*#__PURE__*/_react.default.createElement(_elements.Header, {
    title: t('Screens.EnterPIN'),
    headerTitleStyle: TextTheme.headerTitle,
    headerStyle: {
      height: headerHeight
    },
    headerLeft: renderHeaderLeft
  }), /*#__PURE__*/_react.default.createElement(_PINEnter.default, {
    usage: _PINEnter.PINEntryUsage.ChangeBiometrics,
    setAuthenticated: onAuthenticationComplete,
    onCancelAuth: setCanSeeCheckPIN
  })));
};
var _default = exports.default = ToggleBiometry;
//# sourceMappingURL=ToggleBiometry.js.map