import { CommonActions, useNavigation } from '@react-navigation/native';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, Text, View, Modal, ScrollView, DeviceEventEmitter, Linking, Platform } from 'react-native';
import { PERMISSIONS, RESULTS, request, check } from 'react-native-permissions';
import { SafeAreaView } from 'react-native-safe-area-context';
import Button, { ButtonType } from '../components/buttons/Button';
import ToggleButton from '../components/buttons/ToggleButton';
import { EventTypes } from '../constants';
import { useAnimatedComponents } from '../contexts/animated-components';
import { useAuth } from '../contexts/auth';
import { DispatchAction } from '../contexts/reducers/store';
import { useStore } from '../contexts/store';
import { useTheme } from '../contexts/theme';
import { Screens } from '../types/navigators';
import { testIdWithKey } from '../utils/testable';
import DismissiblePopupModal from '../components/modals/DismissiblePopupModal';
import PINEnter, { PINEntryUsage } from './PINEnter';
import { TOKENS, useServices } from '../container-api';
var UseBiometryUsage = /*#__PURE__*/function (UseBiometryUsage) {
  UseBiometryUsage[UseBiometryUsage["InitialSetup"] = 0] = "InitialSetup";
  UseBiometryUsage[UseBiometryUsage["ToggleOnOff"] = 1] = "ToggleOnOff";
  return UseBiometryUsage;
}(UseBiometryUsage || {});
const UseBiometry = () => {
  const [store, dispatch] = useStore();
  const {
    t
  } = useTranslation();
  const [{
    enablePushNotifications
  }] = useServices([TOKENS.CONFIG]);
  const {
    isBiometricsActive,
    commitPIN,
    disableBiometrics
  } = useAuth();
  const [biometryAvailable, setBiometryAvailable] = useState(false);
  const [biometryEnabled, setBiometryEnabled] = useState(store.preferences.useBiometry);
  const [continueEnabled, setContinueEnabled] = useState(true);
  const [settingsPopupConfig, setSettingsPopupConfig] = useState(null);
  const [canSeeCheckPIN, setCanSeeCheckPIN] = useState(false);
  const {
    ColorPallet,
    TextTheme,
    Assets
  } = useTheme();
  const {
    ButtonLoading
  } = useAnimatedComponents();
  const navigation = useNavigation();
  const screenUsage = useMemo(() => {
    return store.onboarding.didCompleteOnboarding ? UseBiometryUsage.ToggleOnOff : UseBiometryUsage.InitialSetup;
  }, [store.onboarding.didCompleteOnboarding]);
  const BIOMETRY_PERMISSION = PERMISSIONS.IOS.FACE_ID;
  const styles = StyleSheet.create({
    container: {
      height: '100%',
      padding: 20,
      backgroundColor: ColorPallet.brand.primaryBackground
    },
    image: {
      minWidth: 200,
      minHeight: 200,
      marginBottom: 66
    }
  });
  useEffect(() => {
    isBiometricsActive().then(result => {
      setBiometryAvailable(result);
    });
  }, [isBiometricsActive]);
  useEffect(() => {
    if (screenUsage === UseBiometryUsage.InitialSetup) {
      return;
    }
    if (biometryEnabled) {
      commitPIN(biometryEnabled).then(() => {
        dispatch({
          type: DispatchAction.USE_BIOMETRY,
          payload: [biometryEnabled]
        });
      });
    } else {
      disableBiometrics().then(() => {
        dispatch({
          type: DispatchAction.USE_BIOMETRY,
          payload: [biometryEnabled]
        });
      });
    }
  }, [screenUsage, biometryEnabled, commitPIN, disableBiometrics, dispatch]);
  const continueTouched = useCallback(async () => {
    setContinueEnabled(false);
    await commitPIN(biometryEnabled);
    dispatch({
      type: DispatchAction.USE_BIOMETRY,
      payload: [biometryEnabled]
    });
    if (enablePushNotifications) {
      navigation.dispatch(CommonActions.reset({
        index: 0,
        routes: [{
          name: Screens.UsePushNotifications
        }]
      }));
    } else {
      dispatch({
        type: DispatchAction.DID_COMPLETE_ONBOARDING,
        payload: [true]
      });
    }
  }, [biometryEnabled, commitPIN, dispatch, enablePushNotifications, navigation]);
  const onOpenSettingsTouched = async () => {
    await Linking.openSettings();
    onOpenSettingsDismissed();
  };
  const onOpenSettingsDismissed = () => {
    setSettingsPopupConfig(null);
  };
  const onSwitchToggleAllowed = useCallback(newValue => {
    if (screenUsage === UseBiometryUsage.ToggleOnOff) {
      setCanSeeCheckPIN(true);
      DeviceEventEmitter.emit(EventTypes.BIOMETRY_UPDATE, true);
    } else {
      setBiometryEnabled(newValue);
    }
  }, [screenUsage]);
  const onRequestSystemBiometrics = useCallback(async newToggleValue => {
    const permissionResult = await request(BIOMETRY_PERMISSION);
    switch (permissionResult) {
      case RESULTS.GRANTED:
      case RESULTS.LIMITED:
        // Granted
        onSwitchToggleAllowed(newToggleValue);
        break;
      default:
        break;
    }
  }, [onSwitchToggleAllowed, BIOMETRY_PERMISSION]);
  const onCheckSystemBiometrics = useCallback(async () => {
    if (Platform.OS === 'android') {
      // Android doesn't need to prompt biometric permission 
      // for an app to use it.
      return biometryAvailable ? RESULTS.GRANTED : RESULTS.UNAVAILABLE;
    } else if (Platform.OS === 'ios') {
      return await check(BIOMETRY_PERMISSION);
    }
    return RESULTS.UNAVAILABLE;
  }, [biometryAvailable, BIOMETRY_PERMISSION]);
  const toggleSwitch = 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 RESULTS.GRANTED:
      case RESULTS.LIMITED:
        // Already granted
        onSwitchToggleAllowed(newValue);
        break;
      case RESULTS.UNAVAILABLE:
        setSettingsPopupConfig({
          title: t('Biometry.SetupBiometricsTitle'),
          description: t('Biometry.SetupBiometricsDesc')
        });
        break;
      case RESULTS.BLOCKED:
        // Previously denied
        setSettingsPopupConfig({
          title: t('Biometry.AllowBiometricsTitle'),
          description: t('Biometry.AllowBiometricsDesc')
        });
        break;
      case RESULTS.DENIED:
        // Has not been requested
        await onRequestSystemBiometrics(newValue);
        break;
      default:
        break;
    }
  }, [onSwitchToggleAllowed, onRequestSystemBiometrics, onCheckSystemBiometrics, biometryEnabled, t]);
  const onAuthenticationComplete = useCallback(status => {
    // If successfully authenticated the toggle may proceed.
    if (status) {
      setBiometryEnabled(previousState => !previousState);
    }
    DeviceEventEmitter.emit(EventTypes.BIOMETRY_UPDATE, false);
    setCanSeeCheckPIN(false);
  }, []);
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    edges: ['left', 'right', 'bottom']
  }, settingsPopupConfig && /*#__PURE__*/React.createElement(DismissiblePopupModal, {
    title: settingsPopupConfig.title,
    description: settingsPopupConfig.description,
    onCallToActionLabel: t('Biometry.OpenSettings'),
    onCallToActionPressed: onOpenSettingsTouched,
    onDismissPressed: onOpenSettingsDismissed
  }), /*#__PURE__*/React.createElement(ScrollView, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(View, {
    style: {
      alignItems: 'center'
    }
  }, /*#__PURE__*/React.createElement(Assets.svg.biometrics, {
    style: styles.image
  })), biometryAvailable ? /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Text, {
    style: TextTheme.normal
  }, t('Biometry.EnabledText1')), /*#__PURE__*/React.createElement(Text, null), /*#__PURE__*/React.createElement(Text, {
    style: TextTheme.normal
  }, t('Biometry.EnabledText2'), /*#__PURE__*/React.createElement(Text, {
    style: TextTheme.bold
  }, " ", t('Biometry.Warning')))) : /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Text, {
    style: TextTheme.normal
  }, t('Biometry.NotEnabledText1')), /*#__PURE__*/React.createElement(Text, null), /*#__PURE__*/React.createElement(Text, {
    style: TextTheme.normal
  }, t('Biometry.NotEnabledText2'))), /*#__PURE__*/React.createElement(View, {
    style: {
      flexDirection: 'row',
      marginVertical: 20
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: {
      flexShrink: 1,
      marginRight: 10,
      justifyContent: 'center'
    }
  }, /*#__PURE__*/React.createElement(Text, {
    style: TextTheme.bold
  }, t('Biometry.UseToUnlock'))), /*#__PURE__*/React.createElement(View, {
    style: {
      justifyContent: 'center'
    }
  }, /*#__PURE__*/React.createElement(ToggleButton, {
    testID: testIdWithKey("ToggleBiometrics"),
    isEnabled: biometryEnabled,
    isAvailable: true,
    toggleAction: toggleSwitch,
    disabled: false,
    enabledIcon: "check",
    disabledIcon: "close"
  })))), /*#__PURE__*/React.createElement(View, {
    style: {
      marginTop: 'auto',
      margin: 20
    }
  }, store.onboarding.didCompleteOnboarding || /*#__PURE__*/React.createElement(Button, {
    title: 'Continue',
    accessibilityLabel: 'Continue',
    testID: testIdWithKey('Continue'),
    onPress: continueTouched,
    buttonType: ButtonType.Primary,
    disabled: !continueEnabled
  }, !continueEnabled && /*#__PURE__*/React.createElement(ButtonLoading, null))), /*#__PURE__*/React.createElement(Modal, {
    style: {
      backgroundColor: ColorPallet.brand.primaryBackground
    },
    visible: canSeeCheckPIN,
    transparent: false,
    animationType: 'slide'
  }, /*#__PURE__*/React.createElement(PINEnter, {
    usage: PINEntryUsage.PINCheck,
    setAuthenticated: onAuthenticationComplete
  })));
};
export default UseBiometry;
//# sourceMappingURL=UseBiometry.js.map