import { useAgent } from '@aries-framework/react-hooks';
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Platform } from 'react-native';
import { check, PERMISSIONS, request, RESULTS } from 'react-native-permissions';
import Toast from 'react-native-toast-message';
import NewQRView from '../components/misc/NewQRView';
import QRScanner from '../components/misc/QRScanner';
import CameraDisclosureModal from '../components/modals/CameraDisclosureModal';
import { ToastType } from '../components/toast/BaseToast';
import LoadingView from '../components/views/LoadingView';
import { useStore } from '../contexts/store';
import { BifoldError, QrCodeScanError } from '../types/error';
import { Screens, Stacks } from '../types/navigators';
import { connectFromInvitation, getJson, getUrl, receiveMessageFromUrlRedirect } from '../utils/helpers';
const Scan = _ref => {
  let {
    navigation,
    route
  } = _ref;
  const {
    agent
  } = useAgent();
  const {
    t
  } = useTranslation();
  const [store] = useStore();
  const [loading, setLoading] = useState(true);
  const [showDisclosureModal, setShowDisclosureModal] = useState(true);
  const [qrCodeScanError, setQrCodeScanError] = useState(null);
  let defaultToConnect = false;
  if (route !== null && route !== void 0 && route.params && route.params['defaultToConnect']) {
    defaultToConnect = route.params['defaultToConnect'];
  }
  let implicitInvitations = false;
  if (route !== null && route !== void 0 && route.params && route.params['implicitInvitations']) {
    implicitInvitations = route.params['implicitInvitations'];
  }
  let reuseConnections = false;
  if (route !== null && route !== void 0 && route.params && route.params['reuseConnections']) {
    reuseConnections = route.params['reuseConnections'];
  }
  let useMultUseInvitation = false;
  if (route !== null && route !== void 0 && route.params && route.params['useMultUseInvitation']) {
    useMultUseInvitation = route.params['useMultUseInvitation'];
  }
  const handleInvitation = async value => {
    try {
      var _receivedInvitation$c;
      const receivedInvitation = await connectFromInvitation(value, agent, implicitInvitations, reuseConnections, useMultUseInvitation);
      if (receivedInvitation !== null && receivedInvitation !== void 0 && (_receivedInvitation$c = receivedInvitation.connectionRecord) !== null && _receivedInvitation$c !== void 0 && _receivedInvitation$c.id) {
        var _navigation$getParent;
        // not connectionless
        (_navigation$getParent = navigation.getParent()) === null || _navigation$getParent === void 0 ? void 0 : _navigation$getParent.navigate(Stacks.ConnectionStack, {
          screen: Screens.Connection,
          params: {
            connectionId: receivedInvitation.connectionRecord.id
          }
        });
      } else {
        //connectionless
        navigation.navigate(Stacks.ConnectionStack, {
          screen: Screens.Connection,
          params: {
            threadId: receivedInvitation === null || receivedInvitation === void 0 ? void 0 : receivedInvitation.outOfBandRecord.outOfBandInvitation.threadId
          }
        });
      }
    } catch (err) {
      // [Error: Connection does not have an ID]
      // [AriesFrameworkError: An out of band record with invitation 05fe3693-2c12-4165-a3b6-370280ccd43b has already been received. Invitations should have a unique id.]
      try {
        // if scanned value is json -> pass into AFJ as is
        const json = getJson(value);
        if (json) {
          var _navigation$getParent2;
          await (agent === null || agent === void 0 ? void 0 : agent.receiveMessage(json));
          (_navigation$getParent2 = navigation.getParent()) === null || _navigation$getParent2 === void 0 ? void 0 : _navigation$getParent2.navigate(Stacks.ConnectionStack, {
            screen: Screens.Connection,
            params: {
              threadId: json['@id']
            }
          });
          return;
        }

        // if scanned value is url -> receive message from it
        const url = getUrl(value);
        if (url) {
          var _navigation$getParent3;
          const message = await receiveMessageFromUrlRedirect(value, agent);
          (_navigation$getParent3 = navigation.getParent()) === null || _navigation$getParent3 === void 0 ? void 0 : _navigation$getParent3.navigate(Stacks.ConnectionStack, {
            screen: Screens.Connection,
            params: {
              threadId: message['@id']
            }
          });
          return;
        }
      } catch (err) {
        const error = new BifoldError(t('Error.Title1031'), t('Error.Message1031'), (err === null || err === void 0 ? void 0 : err.message) ?? err, 1031);
        // throwing for QrCodeScanError
        throw error;
      }
    }
  };
  const handleCodeScan = async value => {
    setQrCodeScanError(null);
    try {
      const uri = value;
      await handleInvitation(uri);
    } catch (e) {
      const error = new QrCodeScanError(t('Scan.InvalidQrCode'), value);
      setQrCodeScanError(error);
    }
  };
  const permissionFlow = async (method, permission, rationale) => {
    try {
      const permissionResult = await method(permission, rationale);
      if (permissionResult === RESULTS.GRANTED) {
        setShowDisclosureModal(false);
        return true;
      }
    } catch (error) {
      Toast.show({
        type: ToastType.Error,
        text1: t('Global.Failure'),
        text2: (error === null || error === void 0 ? void 0 : error.message) || t('Error.Unknown'),
        visibilityTime: 2000,
        position: 'bottom'
      });
    }
    return false;
  };
  const requestCameraUse = async rationale => {
    if (Platform.OS === 'android') {
      return await permissionFlow(request, PERMISSIONS.ANDROID.CAMERA, rationale);
    } else if (Platform.OS === 'ios') {
      return await permissionFlow(request, PERMISSIONS.IOS.CAMERA, rationale);
    }
    return false;
  };
  useEffect(() => {
    const asyncEffect = async () => {
      if (Platform.OS === 'android') {
        await permissionFlow(check, PERMISSIONS.ANDROID.CAMERA);
      } else if (Platform.OS === 'ios') {
        await permissionFlow(check, PERMISSIONS.IOS.CAMERA);
      }
      setLoading(false);
    };
    asyncEffect();
  }, []);
  if (loading) {
    return /*#__PURE__*/React.createElement(LoadingView, null);
  }
  if (showDisclosureModal) {
    return /*#__PURE__*/React.createElement(CameraDisclosureModal, {
      requestCameraUse: requestCameraUse
    });
  }
  if (store.preferences.useConnectionInviterCapability) {
    return /*#__PURE__*/React.createElement(NewQRView, {
      defaultToConnect: defaultToConnect,
      handleCodeScan: handleCodeScan,
      error: qrCodeScanError,
      enableCameraOnError: true,
      navigation: navigation,
      route: route
    });
  } else {
    return /*#__PURE__*/React.createElement(QRScanner, {
      handleCodeScan: handleCodeScan,
      error: qrCodeScanError,
      enableCameraOnError: true
    });
  }
};
export default Scan;
//# sourceMappingURL=Scan.js.map