"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _core = require("@aries-framework/core");
var _reactHooks = require("@aries-framework/react-hooks");
var _ariesBifoldVerifier = require("@hyperledger/aries-bifold-verifier");
var _core2 = require("@react-navigation/core");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _reactNative = require("react-native");
var _reactNativeGiftedChat = require("react-native-gifted-chat");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _InfoIcon = _interopRequireDefault(require("../components/buttons/InfoIcon"));
var _chat = require("../components/chat");
var _ActionSlider = _interopRequireDefault(require("../components/chat/ActionSlider"));
var _ChatActions = require("../components/chat/ChatActions");
var _ChatEvent = require("../components/chat/ChatEvent");
var _ChatMessage = require("../components/chat/ChatMessage");
var _network = require("../contexts/network");
var _store = require("../contexts/store");
var _theme = require("../contexts/theme");
var _credentials = require("../hooks/credentials");
var _proofs = require("../hooks/proofs");
var _chat2 = require("../types/chat");
var _metadata = require("../types/metadata");
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 Chat = _ref => {
  let {
    route
  } = _ref;
  if (!(route !== null && route !== void 0 && route.params)) {
    throw new Error('Chat route params were not set properly');
  }
  const {
    connectionId
  } = route.params;
  const [store] = (0, _store.useStore)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const {
    agent
  } = (0, _reactHooks.useAgent)();
  const navigation = (0, _core2.useNavigation)();
  const connection = (0, _reactHooks.useConnectionById)(connectionId);
  const basicMessages = (0, _reactHooks.useBasicMessagesByConnectionId)(connectionId);
  const credentials = (0, _credentials.useCredentialsByConnectionId)(connectionId);
  const proofs = (0, _proofs.useProofsByConnectionId)(connectionId);
  const isFocused = (0, _core2.useIsFocused)();
  const {
    assertConnectedNetwork,
    silentAssertConnectedNetwork
  } = (0, _network.useNetwork)();
  const [messages, setMessages] = (0, _react.useState)([]);
  const [showActionSlider, setShowActionSlider] = (0, _react.useState)(false);
  const {
    ChatTheme: theme,
    Assets
  } = (0, _theme.useTheme)();
  const {
    ColorPallet
  } = (0, _theme.useTheme)();
  const [theirLabel, setTheirLabel] = (0, _react.useState)((0, _helpers.getConnectionName)(connection, store.preferences.alternateContactNames));

  // This useEffect is for properly rendering changes to the alt contact name, useMemo did not pick them up
  (0, _react.useEffect)(() => {
    setTheirLabel((0, _helpers.getConnectionName)(connection, store.preferences.alternateContactNames));
  }, [isFocused, connection, store.preferences.alternateContactNames]);
  (0, _react.useMemo)(() => {
    assertConnectedNetwork();
  }, []);
  (0, _react.useEffect)(() => {
    navigation.setOptions({
      title: theirLabel,
      headerRight: () => /*#__PURE__*/_react.default.createElement(_InfoIcon.default, {
        connectionId: connection === null || connection === void 0 ? void 0 : connection.id
      })
    });
  }, [connection, theirLabel]);

  // when chat is open, mark messages as seen
  (0, _react.useEffect)(() => {
    basicMessages.forEach(msg => {
      const meta = msg.metadata.get(_metadata.BasicMessageMetadata.customMetadata);
      if (agent && !(meta !== null && meta !== void 0 && meta.seen)) {
        msg.metadata.set(_metadata.BasicMessageMetadata.customMetadata, {
          ...meta,
          seen: true
        });
        const basicMessageRepository = agent.context.dependencyManager.resolve(_core.BasicMessageRepository);
        basicMessageRepository.update(agent.context, msg);
      }
    });
  }, [basicMessages]);
  (0, _react.useEffect)(() => {
    const transformedMessages = basicMessages.map(record => {
      const role = (0, _helpers.getMessageEventRole)(record);
      // eslint-disable-next-line
      const linkRegex = /(?:https?\:\/\/\w+(?:\.\w+)+\S*)|(?:[\w\d\.\_\-]+@\w+(?:\.\w+)+)/gm;
      // eslint-disable-next-line
      const mailRegex = /^[\w\d\.\_\-]+@\w+(?:\.\w+)+$/gm;
      const links = record.content.match(linkRegex) ?? [];
      const handleLinkPress = link => {
        if (link.match(mailRegex)) {
          link = 'mailto:' + link;
        }
        _reactNative.Linking.openURL(link);
      };
      const msgText = /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
        style: role === _chat2.Role.me ? theme.rightText : theme.leftText
      }, record.content.split(linkRegex).map((split, i) => {
        if (i < links.length) {
          const link = links[i];
          return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactNative.Text, null, split), /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
            onPress: () => handleLinkPress(link),
            style: {
              color: ColorPallet.brand.link,
              textDecorationLine: 'underline'
            },
            accessibilityRole: 'link'
          }, link));
        }
        return /*#__PURE__*/_react.default.createElement(_reactNative.Text, null, split);
      }));
      return {
        _id: record.id,
        text: record.content,
        renderEvent: () => msgText,
        createdAt: record.updatedAt || record.createdAt,
        type: record.type,
        user: {
          _id: role
        }
      };
    });
    const callbackTypeForMessage = record => {
      if (record instanceof _core.CredentialExchangeRecord && (record.state === _core.CredentialState.Done || record.state === _core.CredentialState.OfferReceived)) {
        return _ChatMessage.CallbackType.CredentialOffer;
      }
      if (record instanceof _core.ProofExchangeRecord && (0, _ariesBifoldVerifier.isPresentationReceived)(record) && record.isVerified !== undefined || record.state === _core.ProofState.RequestReceived || record.state === _core.ProofState.Done && record.isVerified === undefined) {
        return _ChatMessage.CallbackType.ProofRequest;
      }
      if (record instanceof _core.ProofExchangeRecord && (record.state === _core.ProofState.PresentationSent || record.state === _core.ProofState.Done)) {
        return _ChatMessage.CallbackType.PresentationSent;
      }
    };
    transformedMessages.push(...credentials.map(record => {
      const role = (0, _helpers.getCredentialEventRole)(record);
      const userLabel = role === _chat2.Role.me ? t('Chat.UserYou') : theirLabel;
      const actionLabel = t((0, _helpers.getCredentialEventLabel)(record));
      return {
        _id: record.id,
        text: actionLabel,
        renderEvent: () => /*#__PURE__*/_react.default.createElement(_ChatEvent.ChatEvent, {
          role: role,
          userLabel: userLabel,
          actionLabel: actionLabel
        }),
        createdAt: record.updatedAt || record.createdAt,
        type: record.type,
        user: {
          _id: role
        },
        messageOpensCallbackType: callbackTypeForMessage(record),
        onDetails: () => {
          const navMap = {
            [_core.CredentialState.Done]: () => {
              navigation.navigate(_navigators.Stacks.ContactStack, {
                screen: _navigators.Screens.CredentialDetails,
                params: {
                  credential: record
                }
              });
            },
            [_core.CredentialState.OfferReceived]: () => {
              navigation.navigate(_navigators.Stacks.ContactStack, {
                screen: _navigators.Screens.CredentialOffer,
                params: {
                  credentialId: record.id
                }
              });
            }
          };
          const nav = navMap[record.state];
          if (nav) {
            nav();
          }
        }
      };
    }));
    transformedMessages.push(...proofs.map(record => {
      const role = (0, _helpers.getProofEventRole)(record);
      const userLabel = role === _chat2.Role.me ? t('Chat.UserYou') : theirLabel;
      const actionLabel = t((0, _helpers.getProofEventLabel)(record));
      return {
        _id: record.id,
        text: actionLabel,
        renderEvent: () => /*#__PURE__*/_react.default.createElement(_ChatEvent.ChatEvent, {
          role: role,
          userLabel: userLabel,
          actionLabel: actionLabel
        }),
        createdAt: record.updatedAt || record.createdAt,
        type: record.type,
        user: {
          _id: role
        },
        messageOpensCallbackType: callbackTypeForMessage(record),
        onDetails: () => {
          const toProofDetails = () => {
            navigation.navigate(_navigators.Stacks.ContactStack, {
              screen: _navigators.Screens.ProofDetails,
              params: {
                recordId: record.id,
                isHistory: true,
                senderReview: record.state === _core.ProofState.PresentationSent || record.state === _core.ProofState.Done && record.isVerified === undefined
              }
            });
          };
          const navMap = {
            [_core.ProofState.Done]: toProofDetails,
            [_core.ProofState.PresentationSent]: toProofDetails,
            [_core.ProofState.PresentationReceived]: toProofDetails,
            [_core.ProofState.RequestReceived]: () => {
              navigation.navigate(_navigators.Stacks.ContactStack, {
                screen: _navigators.Screens.ProofRequest,
                params: {
                  proofId: record.id
                }
              });
            }
          };
          const nav = navMap[record.state];
          if (nav) {
            nav();
          }
        }
      };
    }));
    const connectedMessage = connection ? {
      _id: 'connected',
      text: `${t('Chat.YouConnected')} ${theirLabel}`,
      renderEvent: () => /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
        style: theme.rightText
      }, t('Chat.YouConnected'), /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
        style: [theme.rightText, theme.rightTextHighlighted]
      }, " ", theirLabel)),
      createdAt: connection.createdAt,
      user: {
        _id: _chat2.Role.me
      }
    } : undefined;
    setMessages(connectedMessage ? [...transformedMessages.sort((a, b) => b.createdAt - a.createdAt), connectedMessage] : transformedMessages.sort((a, b) => b.createdAt - a.createdAt));
  }, [basicMessages, credentials, proofs, theirLabel]);
  const onSend = (0, _react.useCallback)(async messages => {
    await (agent === null || agent === void 0 ? void 0 : agent.basicMessages.sendMessage(connectionId, messages[0].text));
  }, [agent, connectionId]);
  const onSendRequest = (0, _react.useCallback)(async () => {
    navigation.navigate(_navigators.Stacks.ProofRequestsStack, {
      screen: _navigators.Screens.ProofRequests,
      params: {
        navigation: navigation,
        connectionId
      }
    });
  }, [navigation, connectionId]);
  const actions = (0, _react.useMemo)(() => {
    return store.preferences.useVerifierCapability ? [{
      text: t('Verifier.SendProofRequest'),
      onPress: () => {
        setShowActionSlider(false);
        onSendRequest();
      },
      icon: () => /*#__PURE__*/_react.default.createElement(Assets.svg.iconInfoSentDark, {
        height: 30,
        width: 30
      })
    }] : undefined;
  }, [t, store.preferences.useVerifierCapability, onSendRequest]);
  const onDismiss = () => {
    setShowActionSlider(false);
  };
  return /*#__PURE__*/_react.default.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    edges: ['bottom', 'left', 'right'],
    style: {
      flex: 1,
      paddingTop: 20
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNativeGiftedChat.GiftedChat, {
    messages: messages,
    showAvatarForEveryMessage: true,
    alignTop: true,
    renderAvatar: () => null,
    messageIdGenerator: msg => (msg === null || msg === void 0 ? void 0 : msg._id.toString()) || '0',
    renderMessage: props => /*#__PURE__*/_react.default.createElement(_ChatMessage.ChatMessage, {
      messageProps: props
    }),
    renderInputToolbar: props => (0, _chat.renderInputToolbar)(props, theme),
    renderSend: props => (0, _chat.renderSend)(props, theme),
    renderComposer: props => (0, _chat.renderComposer)(props, theme, t('Contacts.TypeHere')),
    disableComposer: !silentAssertConnectedNetwork(),
    onSend: onSend,
    user: {
      _id: _chat2.Role.me
    },
    renderActions: props => (0, _ChatActions.renderActions)(props, theme, actions),
    onPressActionButton: actions ? () => setShowActionSlider(true) : undefined
  }), showActionSlider && /*#__PURE__*/_react.default.createElement(_ActionSlider.default, {
    onDismiss: onDismiss,
    actions: actions
  }));
};
var _default = Chat;
exports.default = _default;
//# sourceMappingURL=Chat.js.map