"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _reactHooks = require("@aries-framework/react-hooks");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _reactNative = require("react-native");
var _reactNativePermissions = require("react-native-permissions");
var _reactNativeToastMessage = _interopRequireDefault(require("react-native-toast-message"));
var _NewQRView = _interopRequireDefault(require("../components/misc/NewQRView"));
var _QRScanner = _interopRequireDefault(require("../components/misc/QRScanner"));
var _CameraDisclosureModal = _interopRequireDefault(require("../components/modals/CameraDisclosureModal"));
var _BaseToast = require("../components/toast/BaseToast");
var _LoadingView = _interopRequireDefault(require("../components/views/LoadingView"));
var _store = require("../contexts/store");
var _error = require("../types/error");
var _navigators = require("../types/navigators");
var _helpers = require("../utils/helpers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const Scan = _ref => {
  let {
    navigation,
    route
  } = _ref;
  const {
    agent
  } = (0, _reactHooks.useAgent)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const [store] = (0, _store.useStore)();
  const [loading, setLoading] = (0, _react.useState)(true);
  const [showDisclosureModal, setShowDisclosureModal] = (0, _react.useState)(true);
  const [qrCodeScanError, setQrCodeScanError] = (0, _react.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'];
  }
  const handleInvitation = async value => {
    try {
      var _receivedInvitation$c;
      const receivedInvitation = await (0, _helpers.connectFromInvitation)(value, agent, implicitInvitations, reuseConnections);
      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(_navigators.Stacks.ConnectionStack, {
          screen: _navigators.Screens.Connection,
          params: {
            connectionId: receivedInvitation.connectionRecord.id
          }
        });
      } else {
        //connectionless
        navigation.navigate(_navigators.Stacks.ConnectionStack, {
          screen: _navigators.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 = (0, _helpers.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(_navigators.Stacks.ConnectionStack, {
            screen: _navigators.Screens.Connection,
            params: {
              threadId: json['@id']
            }
          });
          return;
        }

        // if scanned value is url -> receive message from it
        const url = (0, _helpers.getUrl)(value);
        if (url) {
          var _navigation$getParent3;
          const message = await (0, _helpers.receiveMessageFromUrlRedirect)(value, agent);
          (_navigation$getParent3 = navigation.getParent()) === null || _navigation$getParent3 === void 0 ? void 0 : _navigation$getParent3.navigate(_navigators.Stacks.ConnectionStack, {
            screen: _navigators.Screens.Connection,
            params: {
              threadId: message['@id']
            }
          });
          return;
        }
      } catch (err) {
        const error = new _error.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 _error.QrCodeScanError(t('Scan.InvalidQrCode'), value);
      setQrCodeScanError(error);
    }
  };
  const permissionFlow = async (method, permission, rationale) => {
    try {
      const permissionResult = await method(permission, rationale);
      if (permissionResult === _reactNativePermissions.RESULTS.GRANTED) {
        setShowDisclosureModal(false);
        return true;
      }
    } catch (error) {
      _reactNativeToastMessage.default.show({
        type: _BaseToast.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 (_reactNative.Platform.OS === 'android') {
      return await permissionFlow(_reactNativePermissions.request, _reactNativePermissions.PERMISSIONS.ANDROID.CAMERA, rationale);
    } else if (_reactNative.Platform.OS === 'ios') {
      return await permissionFlow(_reactNativePermissions.request, _reactNativePermissions.PERMISSIONS.IOS.CAMERA, rationale);
    }
    return false;
  };
  (0, _react.useEffect)(() => {
    const asyncEffect = async () => {
      if (_reactNative.Platform.OS === 'android') {
        await permissionFlow(_reactNativePermissions.check, _reactNativePermissions.PERMISSIONS.ANDROID.CAMERA);
      } else if (_reactNative.Platform.OS === 'ios') {
        await permissionFlow(_reactNativePermissions.check, _reactNativePermissions.PERMISSIONS.IOS.CAMERA);
      }
      setLoading(false);
    };
    asyncEffect();
  }, []);
  if (loading) {
    return /*#__PURE__*/_react.default.createElement(_LoadingView.default, null);
  }
  if (showDisclosureModal) {
    return /*#__PURE__*/_react.default.createElement(_CameraDisclosureModal.default, {
      requestCameraUse: requestCameraUse
    });
  }
  if (store.preferences.useConnectionInviterCapability) {
    return /*#__PURE__*/_react.default.createElement(_NewQRView.default, {
      defaultToConnect: defaultToConnect,
      handleCodeScan: handleCodeScan,
      error: qrCodeScanError,
      enableCameraOnError: true,
      navigation: navigation,
      route: route
    });
  } else {
    return /*#__PURE__*/_react.default.createElement(_QRScanner.default, {
      handleCodeScan: handleCodeScan,
      error: qrCodeScanError,
      enableCameraOnError: true
    });
  }
};
var _default = Scan;
exports.default = _default;
//# sourceMappingURL=Scan.js.map