import { DidExchangeState } from '@aries-framework/core';
import { useAgent } from '@aries-framework/react-hooks';
import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Vibration, View, StyleSheet, Text, ScrollView, useWindowDimensions } from 'react-native';
import { RNCamera } from 'react-native-camera';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { SafeAreaView } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { useStore } from '../../contexts/store';
import { useTheme } from '../../contexts/theme';
import { useConnectionByOutOfBandId } from '../../hooks/connections';
import { Screens, Stacks } from '../../types/navigators';
import { createConnectionInvitation } from '../../utils/helpers';
import { testIdWithKey } from '../../utils/testable';
import LoadingIndicator from '../animated/LoadingIndicator';
import QRRenderer from './QRRenderer';
import QRScannerTorch from './QRScannerTorch';
import ScanTab from './ScanTab';
const NewQRView = _ref => {
  let {
    defaultToConnect,
    handleCodeScan,
    error,
    enableCameraOnError,
    navigation
  } = _ref;
  const {
    width
  } = useWindowDimensions();
  const qrSize = width - 40;
  const [store] = useStore();
  const [cameraActive, setCameraActive] = useState(true);
  const [torchActive, setTorchActive] = useState(false);
  const [firstTabActive, setFirstTabActive] = useState(!defaultToConnect);
  const [invitation, setInvitation] = useState(undefined);
  const [recordId, setRecordId] = useState(undefined);
  const {
    t
  } = useTranslation();
  const invalidQrCodes = new Set();
  const {
    ColorPallet,
    TextTheme,
    TabTheme
  } = useTheme();
  const {
    agent
  } = useAgent();
  const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: ColorPallet.brand.secondaryBackground
    },
    camera: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center'
    },
    cameraViewContainer: {
      alignItems: 'center',
      flex: 1,
      width: '100%'
    },
    viewFinder: {
      width: 250,
      height: 250,
      borderRadius: 24,
      borderWidth: 2,
      borderColor: ColorPallet.grayscale.white
    },
    viewFinderContainer: {
      flex: 1,
      width: '100%',
      justifyContent: 'center',
      alignItems: 'center'
    },
    errorContainer: {
      flexDirection: 'row',
      alignItems: 'center',
      marginTop: 20,
      paddingHorizontal: 20
    },
    icon: {
      color: ColorPallet.grayscale.white,
      padding: 4
    },
    tabContainer: {
      flexDirection: 'row',
      ...TabTheme.tabBarStyle
    },
    qrContainer: {
      marginTop: 10,
      flex: 1
    },
    walletName: {
      ...TextTheme.headingTwo,
      textAlign: 'center',
      marginBottom: 20
    },
    secondaryText: {
      ...TextTheme.normal,
      textAlign: 'center'
    },
    editButton: {
      ...TextTheme.headingTwo,
      marginBottom: 20,
      marginLeft: 10,
      color: ColorPallet.brand.primary
    }
  });
  const createInvitation = useCallback(async () => {
    setInvitation(undefined);
    const result = await createConnectionInvitation(agent);
    if (result) {
      setRecordId(result.record.id);
      setInvitation(result.invitationUrl);
    }
  }, []);
  const handleEdit = () => {
    navigation.navigate(Screens.NameWallet);
  };
  useEffect(() => {
    navigation.setOptions({
      title: firstTabActive ? 'Scan QR code' : 'My QR code'
    });
    if (!firstTabActive) {
      createInvitation();
    }
  }, [firstTabActive, store.preferences.walletName]);
  const record = useConnectionByOutOfBandId(recordId || '');
  useEffect(() => {
    if ((record === null || record === void 0 ? void 0 : record.state) === DidExchangeState.Completed) {
      var _navigation$getParent;
      (_navigation$getParent = navigation.getParent()) === null || _navigation$getParent === void 0 ? void 0 : _navigation$getParent.navigate(Stacks.ConnectionStack, {
        screen: Screens.Connection,
        params: {
          connectionId: record.id
        }
      });
    }
  }, [record]);
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    edges: ['bottom', 'left', 'right'],
    style: styles.container
  }, firstTabActive ? /*#__PURE__*/React.createElement(RNCamera, {
    style: styles.camera,
    type: RNCamera.Constants.Type.back,
    flashMode: torchActive ? RNCamera.Constants.FlashMode.torch : RNCamera.Constants.FlashMode.off,
    captureAudio: false,
    androidCameraPermissionOptions: {
      title: t('QRScanner.PermissionToUseCamera'),
      message: t('QRScanner.WeNeedYourPermissionToUseYourCamera'),
      buttonPositive: t('QRScanner.Ok'),
      buttonNegative: t('Global.Cancel')
    },
    barCodeTypes: [RNCamera.Constants.BarCodeType.qr],
    onBarCodeRead: event => {
      if (invalidQrCodes.has(event.data)) {
        return;
      }
      if ((error === null || error === void 0 ? void 0 : error.data) === (event === null || event === void 0 ? void 0 : event.data)) {
        invalidQrCodes.add(error.data);
        if (enableCameraOnError) {
          return setCameraActive(true);
        }
      }
      if (cameraActive) {
        Vibration.vibrate();
        handleCodeScan(event);
        return setCameraActive(false);
      }
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.cameraViewContainer
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.errorContainer
  }, error ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Icon, {
    style: styles.icon,
    name: "cancel",
    size: 30
  }), /*#__PURE__*/React.createElement(Text, {
    testID: testIdWithKey('ErrorMessage'),
    style: [TextTheme.normal, {
      color: ColorPallet.grayscale.white
    }]
  }, error.message)) : /*#__PURE__*/React.createElement(Text, {
    style: [TextTheme.normal, {
      color: ColorPallet.grayscale.white
    }]
  }, t('Scan.WillScanAutomatically'))), /*#__PURE__*/React.createElement(View, {
    style: styles.viewFinderContainer
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.viewFinder
  })), /*#__PURE__*/React.createElement(QRScannerTorch, {
    active: torchActive,
    onPress: () => setTorchActive(!torchActive)
  }))) : /*#__PURE__*/React.createElement(ScrollView, null, /*#__PURE__*/React.createElement(View, {
    style: {
      alignItems: 'center'
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.qrContainer
  }, !invitation && /*#__PURE__*/React.createElement(LoadingIndicator, null), invitation && /*#__PURE__*/React.createElement(QRRenderer, {
    value: invitation,
    size: qrSize
  })), /*#__PURE__*/React.createElement(View, {
    style: {
      paddingHorizontal: 20,
      flex: 1
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: {
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/React.createElement(Text, {
    testID: testIdWithKey('WalletName'),
    style: [styles.walletName, {
      paddingHorizontal: 20
    }]
  }, store.preferences.walletName), /*#__PURE__*/React.createElement(TouchableOpacity, {
    accessibilityLabel: t('NameWallet.EditWalletName'),
    testID: testIdWithKey('EditWalletName'),
    onPress: handleEdit
  }, /*#__PURE__*/React.createElement(Icon, {
    style: styles.editButton,
    name: "edit",
    size: 24
  }))), /*#__PURE__*/React.createElement(Text, {
    style: styles.secondaryText
  }, t('Connection.ShareQR'))))), /*#__PURE__*/React.createElement(View, {
    style: styles.tabContainer
  }, /*#__PURE__*/React.createElement(ScanTab, {
    title: t('Scan.ScanQRCode'),
    iconName: 'crop-free',
    onPress: () => setFirstTabActive(true),
    active: firstTabActive
  }), /*#__PURE__*/React.createElement(ScanTab, {
    title: t('Scan.MyQRCode'),
    iconName: 'qr-code',
    onPress: () => setFirstTabActive(false),
    active: !firstTabActive
  })));
};
export default NewQRView;
//# sourceMappingURL=NewQRView.js.map