"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _reactHooks = require("@aries-framework/react-hooks");
var _native = require("@react-navigation/native");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _reactNative = require("react-native");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _Button = _interopRequireWildcard(require("../components/buttons/Button"));
var _animatedComponents = require("../contexts/animated-components");
var _configuration = require("../contexts/configuration");
var _theme = require("../contexts/theme");
var _connections = require("../hooks/connections");
var _notifications = require("../hooks/notifications");
var _navigators = require("../types/navigators");
var _testable = require("../utils/testable");
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 Connection = _ref => {
  let {
    navigation,
    route
  } = _ref;
  // TODO(jl): When implementing goal codes the `autoRedirectConnectionToHome`
  // logic should be: if this property is set, rather than showing the
  // delay message, the user should be redirected to the home screen.
  const {
    connectionTimerDelay,
    autoRedirectConnectionToHome
  } = (0, _configuration.useConfiguration)();
  const connTimerDelay = connectionTimerDelay ?? 10000; // in ms
  const {
    connectionId,
    threadId
  } = route.params;
  const timerRef = (0, _react.useRef)(null);
  const connection = connectionId ? (0, _reactHooks.useConnectionById)(connectionId) : undefined;
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const {
    notifications
  } = (0, _notifications.useNotifications)();
  const {
    ColorPallet,
    TextTheme
  } = (0, _theme.useTheme)();
  const {
    ConnectionLoading
  } = (0, _animatedComponents.useAnimatedComponents)();
  const oobRecord = (0, _connections.useOutOfBandByConnectionId)(connectionId ?? '');
  const goalCode = oobRecord === null || oobRecord === void 0 ? void 0 : oobRecord.outOfBandInvitation.goalCode;
  const merge = (current, next) => ({
    ...current,
    ...next
  });
  const [state, dispatch] = (0, _react.useReducer)(merge, {
    isVisible: true,
    isInitialized: false,
    shouldShowDelayMessage: false,
    connectionIsActive: false
  });
  const styles = _reactNative.StyleSheet.create({
    container: {
      height: '100%',
      backgroundColor: ColorPallet.brand.modalPrimaryBackground,
      padding: 20
    },
    image: {
      marginTop: 20
    },
    messageContainer: {
      alignItems: 'center'
    },
    messageText: {
      fontWeight: 'normal',
      textAlign: 'center',
      marginTop: 30
    },
    controlsContainer: {
      marginTop: 'auto',
      margin: 20
    },
    delayMessageText: {
      textAlign: 'center',
      marginTop: 20
    }
  });
  const goalCodeAction = goalCode => {
    const codes = {
      'aries.vc.verify': () => navigation.navigate(_navigators.Screens.ProofRequest, {
        proofId: state.notificationRecord.id
      }),
      'aries.vc.issue': () => navigation.navigate(_navigators.Screens.CredentialOffer, {
        credentialId: state.notificationRecord.id
      })
    };
    let action = codes[goalCode];
    if (action === undefined) {
      const matchCode = Object.keys(codes).find(code => goalCode.startsWith(code));
      action = codes[matchCode ?? ''];
      if (action === undefined) {
        throw new Error('Unhandled goal code type');
      }
    }
    return action;
  };
  const startTimer = () => {
    if (!state.isInitialized) {
      timerRef.current = setTimeout(() => {
        dispatch({
          shouldShowDelayMessage: true
        });
        timerRef.current = null;
      }, connTimerDelay);
      dispatch({
        isInitialized: true
      });
    }
  };
  const abortTimer = () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
  };
  const onDismissModalTouched = () => {
    var _navigation$getParent;
    dispatch({
      shouldShowDelayMessage: false,
      isVisible: false
    });
    (_navigation$getParent = navigation.getParent()) === null || _navigation$getParent === void 0 ? void 0 : _navigation$getParent.navigate(_navigators.TabStacks.HomeStack, {
      screen: _navigators.Screens.Home
    });
  };
  (0, _react.useEffect)(() => {
    if (state.shouldShowDelayMessage && !state.notificationRecord) {
      if (autoRedirectConnectionToHome) {
        var _navigation$getParent2;
        dispatch({
          shouldShowDelayMessage: false,
          isVisible: false
        });
        (_navigation$getParent2 = navigation.getParent()) === null || _navigation$getParent2 === void 0 ? void 0 : _navigation$getParent2.navigate(_navigators.TabStacks.HomeStack, {
          screen: _navigators.Screens.Home
        });
      } else {
        _reactNative.AccessibilityInfo.announceForAccessibility(t('Connection.TakingTooLong'));
      }
    }
  }, [state.shouldShowDelayMessage]);
  (0, _react.useEffect)(() => {
    if (!connectionId && !oobRecord && !goalCode && state.notificationRecord && state.notificationRecord.state === 'request-received') {
      navigation.navigate(_navigators.Screens.ProofRequest, {
        proofId: state.notificationRecord.id
      });
      dispatch({
        isVisible: false
      });
      return;
    }
    if (connectionId && oobRecord && (!goalCode || !goalCode.startsWith('aries.vc.verify') && !goalCode.startsWith('aries.vc.issue'))) {
      var _navigation$getParent3;
      // No goal code, we don't know what to expect next,
      // navigate to the chat screen and set home screen as only history
      (_navigation$getParent3 = navigation.getParent()) === null || _navigation$getParent3 === void 0 ? void 0 : _navigation$getParent3.dispatch(_native.CommonActions.reset({
        index: 1,
        routes: [{
          name: _navigators.Stacks.TabStack
        }, {
          name: _navigators.Screens.Chat,
          params: {
            connectionId
          }
        }]
      }));
      dispatch({
        isVisible: false
      });
      return;
    }
    if (state.notificationRecord && goalCode) {
      goalCodeAction(goalCode)();
    }
  }, [connection, oobRecord, goalCode, state.notificationRecord]);
  (0, _react.useMemo)(() => {
    startTimer();
    return () => abortTimer;
  }, []);
  (0, _native.useFocusEffect)((0, _react.useCallback)(() => {
    startTimer();
    return () => abortTimer;
  }, []));
  (0, _react.useEffect)(() => {
    if (state.isVisible) {
      for (const notification of notifications) {
        // no action taken for BasicMessageRecords
        if (notification.type !== 'BasicMessageRecord') {
          if (!state.notificationRecord && (connectionId && notification.connectionId === connectionId || threadId && notification.threadId == threadId)) {
            dispatch({
              notificationRecord: notification,
              isVisible: false
            });
            break;
          }
          if (!connection && notification.state === 'request-received') {
            dispatch({
              notificationRecord: notification,
              isVisible: false
            });
            break;
          }
        }
      }
    }
  }, [notifications]);
  return /*#__PURE__*/_react.default.createElement(_reactNative.Modal, {
    visible: state.isVisible,
    transparent: true,
    animationType: 'slide',
    onRequestClose: () => {
      dispatch({
        isVisible: false
      });
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    style: {
      backgroundColor: ColorPallet.brand.modalPrimaryBackground
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.ScrollView, {
    style: [styles.container]
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: [styles.messageContainer]
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: [TextTheme.modalHeadingThree, styles.messageText],
    testID: (0, _testable.testIdWithKey)('CredentialOnTheWay')
  }, t('Connection.JustAMoment'))), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: [styles.image]
  }, /*#__PURE__*/_react.default.createElement(ConnectionLoading, null)), state.shouldShowDelayMessage && /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: [TextTheme.modalNormal, styles.delayMessageText],
    testID: (0, _testable.testIdWithKey)('TakingTooLong')
  }, t('Connection.TakingTooLong'))), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: [styles.controlsContainer]
  }, /*#__PURE__*/_react.default.createElement(_Button.default, {
    title: t('Loading.BackToHome'),
    accessibilityLabel: t('Loading.BackToHome'),
    testID: (0, _testable.testIdWithKey)('BackToHome'),
    onPress: onDismissModalTouched,
    buttonType: _Button.ButtonType.ModalSecondary
  }))));
};
var _default = Connection;
exports.default = _default;
//# sourceMappingURL=Connection.js.map