"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 _reactNativePermissions = require("react-native-permissions");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _Button = _interopRequireWildcard(require("../components/buttons/Button"));
var _ToggleButton = _interopRequireDefault(require("../components/buttons/ToggleButton"));
var _constants = require("../constants");
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 _navigators = require("../types/navigators");
var _testable = require("../utils/testable");
var _DismissiblePopupModal = _interopRequireDefault(require("../components/modals/DismissiblePopupModal"));
var _PINEnter = _interopRequireWildcard(require("./PINEnter"));
var _containerApi = require("../container-api");
var _types = require("../modules/history/types");
var _agent = require("../utils/agent");
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; }
var UseBiometryUsage = /*#__PURE__*/function (UseBiometryUsage) {
  UseBiometryUsage[UseBiometryUsage["InitialSetup"] = 0] = "InitialSetup";
  UseBiometryUsage[UseBiometryUsage["ToggleOnOff"] = 1] = "ToggleOnOff";
  return UseBiometryUsage;
}(UseBiometryUsage || {});
const UseBiometry = () => {
  const [store, dispatch] = (0, _store2.useStore)();
  const {
    agent
  } = (0, _agent.useAppAgent)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const [{
    enablePushNotifications
  }, logger, historyManagerCurried, historyEnabled, historyEventsLogger] = (0, _containerApi.useServices)([_containerApi.TOKENS.CONFIG, _containerApi.TOKENS.UTIL_LOGGER, _containerApi.TOKENS.FN_LOAD_HISTORY, _containerApi.TOKENS.HISTORY_ENABLED, _containerApi.TOKENS.HISTORY_EVENTS_LOGGER]);
  const {
    isBiometricsActive,
    commitPIN,
    disableBiometrics
  } = (0, _auth.useAuth)();
  const [biometryAvailable, setBiometryAvailable] = (0, _react.useState)(false);
  const [biometryEnabled, setBiometryEnabled] = (0, _react.useState)(store.preferences.useBiometry);
  const [continueEnabled, setContinueEnabled] = (0, _react.useState)(true);
  const [settingsPopupConfig, setSettingsPopupConfig] = (0, _react.useState)(null);
  const [canSeeCheckPIN, setCanSeeCheckPIN] = (0, _react.useState)(false);
  const {
    ColorPallet,
    TextTheme,
    Assets
  } = (0, _theme.useTheme)();
  const {
    ButtonLoading
  } = (0, _animatedComponents.useAnimatedComponents)();
  const navigation = (0, _native.useNavigation)();
  const screenUsage = (0, _react.useMemo)(() => {
    return store.onboarding.didCompleteOnboarding ? UseBiometryUsage.ToggleOnOff : UseBiometryUsage.InitialSetup;
  }, [store.onboarding.didCompleteOnboarding]);
  const BIOMETRY_PERMISSION = _reactNativePermissions.PERMISSIONS.IOS.FACE_ID;
  const styles = _reactNative.StyleSheet.create({
    container: {
      height: '100%',
      padding: 20,
      backgroundColor: ColorPallet.brand.primaryBackground
    },
    image: {
      minWidth: 200,
      minHeight: 200,
      marginBottom: 66
    }
  });
  (0, _react.useEffect)(() => {
    isBiometricsActive().then(result => {
      setBiometryAvailable(result);
    });
  }, [isBiometricsActive]);
  (0, _react.useEffect)(() => {
    if (screenUsage === UseBiometryUsage.InitialSetup) {
      return;
    }
    if (biometryEnabled) {
      commitPIN(biometryEnabled).then(() => {
        dispatch({
          type: _store.DispatchAction.USE_BIOMETRY,
          payload: [biometryEnabled]
        });
      });
    } else {
      disableBiometrics().then(() => {
        dispatch({
          type: _store.DispatchAction.USE_BIOMETRY,
          payload: [biometryEnabled]
        });
      });
    }
  }, [screenUsage, biometryEnabled, commitPIN, disableBiometrics, dispatch]);
  const logHistoryRecord = (0, _react.useCallback)(type => {
    try {
      if (!(agent && historyEnabled)) {
        logger.trace(`[${UseBiometry.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(`[${UseBiometry.name}]:[logHistoryRecord] Error saving history: ${err}`);
    }
  }, [agent, historyEnabled, logger, historyManagerCurried]);
  const continueTouched = (0, _react.useCallback)(async () => {
    setContinueEnabled(false);
    await commitPIN(biometryEnabled);
    dispatch({
      type: _store.DispatchAction.USE_BIOMETRY,
      payload: [biometryEnabled]
    });
    if (enablePushNotifications) {
      navigation.dispatch(_native.CommonActions.reset({
        index: 0,
        routes: [{
          name: _navigators.Screens.UsePushNotifications
        }]
      }));
    } else {
      dispatch({
        type: _store.DispatchAction.DID_COMPLETE_ONBOARDING,
        payload: [true]
      });
    }
  }, [biometryEnabled, commitPIN, dispatch, enablePushNotifications, navigation]);
  const onOpenSettingsTouched = async () => {
    await _reactNative.Linking.openSettings();
    onOpenSettingsDismissed();
  };
  const onOpenSettingsDismissed = () => {
    setSettingsPopupConfig(null);
  };
  const onSwitchToggleAllowed = (0, _react.useCallback)(newValue => {
    if (screenUsage === UseBiometryUsage.ToggleOnOff) {
      setCanSeeCheckPIN(true);
      _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.BIOMETRY_UPDATE, true);
      if (historyEventsLogger.logToggleBiometry && store.onboarding.didAgreeToTerms && store.onboarding.didConsiderBiometry) {
        const type = _types.HistoryCardType.ActivateBiometry;
        logHistoryRecord(type);
      }
    } else {
      setBiometryEnabled(newValue);
    }
  }, [screenUsage, historyEventsLogger.logToggleBiometry, logHistoryRecord, store.onboarding.didAgreeToTerms, store.onboarding.didConsiderBiometry]);
  const onRequestSystemBiometrics = (0, _react.useCallback)(async newToggleValue => {
    const permissionResult = await (0, _reactNativePermissions.request)(BIOMETRY_PERMISSION);
    switch (permissionResult) {
      case _reactNativePermissions.RESULTS.GRANTED:
      case _reactNativePermissions.RESULTS.LIMITED:
        // Granted
        onSwitchToggleAllowed(newToggleValue);
        break;
      default:
        break;
    }
  }, [onSwitchToggleAllowed, BIOMETRY_PERMISSION]);
  const onCheckSystemBiometrics = (0, _react.useCallback)(async () => {
    if (_reactNative.Platform.OS === 'android') {
      // Android doesn't need to prompt biometric permission
      // for an app to use it.
      return biometryAvailable ? _reactNativePermissions.RESULTS.GRANTED : _reactNativePermissions.RESULTS.UNAVAILABLE;
    } else if (_reactNative.Platform.OS === 'ios') {
      return await (0, _reactNativePermissions.check)(BIOMETRY_PERMISSION);
    }
    return _reactNativePermissions.RESULTS.UNAVAILABLE;
  }, [biometryAvailable, BIOMETRY_PERMISSION]);
  const toggleSwitch = (0, _react.useCallback)(async () => {
    const newValue = !biometryEnabled;
    if (!newValue) {
      // Turning off doesn't require OS'es biometrics enabled
      onSwitchToggleAllowed(newValue);
      return;
    }

    // If the user is turning it on, they need
    // to first authenticate the OS'es biometrics before this action is accepted
    const permissionResult = await onCheckSystemBiometrics();
    switch (permissionResult) {
      case _reactNativePermissions.RESULTS.GRANTED:
      case _reactNativePermissions.RESULTS.LIMITED:
        // Already granted
        onSwitchToggleAllowed(newValue);
        break;
      case _reactNativePermissions.RESULTS.UNAVAILABLE:
        setSettingsPopupConfig({
          title: t('Biometry.SetupBiometricsTitle'),
          description: t('Biometry.SetupBiometricsDesc')
        });
        break;
      case _reactNativePermissions.RESULTS.BLOCKED:
        // Previously denied
        setSettingsPopupConfig({
          title: t('Biometry.AllowBiometricsTitle'),
          description: t('Biometry.AllowBiometricsDesc')
        });
        break;
      case _reactNativePermissions.RESULTS.DENIED:
        // Has not been requested
        await onRequestSystemBiometrics(newValue);
        break;
      default:
        break;
    }
  }, [onSwitchToggleAllowed, onRequestSystemBiometrics, onCheckSystemBiometrics, biometryEnabled, t]);
  const onAuthenticationComplete = (0, _react.useCallback)(status => {
    // If successfully authenticated the toggle may proceed.
    if (status) {
      setBiometryEnabled(previousState => !previousState);
    }
    _reactNative.DeviceEventEmitter.emit(_constants.EventTypes.BIOMETRY_UPDATE, false);
    if (historyEventsLogger.logToggleBiometry && store.onboarding.didAgreeToTerms && store.onboarding.didConsiderBiometry) {
      const type = _types.HistoryCardType.DeactivateBiometry;
      logHistoryRecord(type);
    }
    setCanSeeCheckPIN(false);
  }, [historyEventsLogger.logToggleBiometry, logHistoryRecord, store.onboarding.didAgreeToTerms, store.onboarding.didConsiderBiometry]);
  return /*#__PURE__*/_react.default.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    edges: ['left', 'right', 'bottom']
  }, settingsPopupConfig && /*#__PURE__*/_react.default.createElement(_DismissiblePopupModal.default, {
    title: settingsPopupConfig.title,
    description: settingsPopupConfig.description,
    onCallToActionLabel: t('Biometry.OpenSettings'),
    onCallToActionPressed: onOpenSettingsTouched,
    onDismissPressed: onOpenSettingsDismissed
  }), /*#__PURE__*/_react.default.createElement(_reactNative.ScrollView, {
    style: styles.container
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      alignItems: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(Assets.svg.biometrics, {
    style: styles.image
  })), biometryAvailable ? /*#__PURE__*/_react.default.createElement(_reactNative.View, null, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: TextTheme.normal
  }, t('Biometry.EnabledText1')), /*#__PURE__*/_react.default.createElement(_reactNative.Text, null), /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: TextTheme.normal
  }, t('Biometry.EnabledText2'), /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: TextTheme.bold
  }, " ", t('Biometry.Warning')))) : /*#__PURE__*/_react.default.createElement(_reactNative.View, null, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: TextTheme.normal
  }, t('Biometry.NotEnabledText1')), /*#__PURE__*/_react.default.createElement(_reactNative.Text, null), /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: TextTheme.normal
  }, t('Biometry.NotEnabledText2'))), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      flexDirection: 'row',
      marginVertical: 20
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      flexShrink: 1,
      marginRight: 10,
      justifyContent: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: TextTheme.bold
  }, t('Biometry.UseToUnlock'))), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      justifyContent: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_ToggleButton.default, {
    testID: (0, _testable.testIdWithKey)('ToggleBiometrics'),
    isEnabled: biometryEnabled,
    isAvailable: true,
    toggleAction: toggleSwitch,
    disabled: false,
    enabledIcon: "check",
    disabledIcon: "close"
  })))), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      marginTop: 'auto',
      margin: 20
    }
  }, store.onboarding.didCompleteOnboarding || /*#__PURE__*/_react.default.createElement(_Button.default, {
    title: 'Continue',
    accessibilityLabel: 'Continue',
    testID: (0, _testable.testIdWithKey)('Continue'),
    onPress: continueTouched,
    buttonType: _Button.ButtonType.Primary,
    disabled: !continueEnabled
  }, !continueEnabled && /*#__PURE__*/_react.default.createElement(ButtonLoading, null))), /*#__PURE__*/_react.default.createElement(_reactNative.Modal, {
    style: {
      backgroundColor: ColorPallet.brand.primaryBackground
    },
    visible: canSeeCheckPIN,
    transparent: false,
    animationType: 'slide'
  }, /*#__PURE__*/_react.default.createElement(_PINEnter.default, {
    usage: _PINEnter.PINEntryUsage.PINCheck,
    setAuthenticated: onAuthenticationComplete
  })));
};
var _default = exports.default = UseBiometry;
//# sourceMappingURL=UseBiometry.js.map