import { BasicMessageRepository, CredentialExchangeRecord, CredentialState, ProofExchangeRecord, ProofState } from '@aries-framework/core';
import { useAgent, useBasicMessagesByConnectionId, useConnectionById } from '@aries-framework/react-hooks';
import { isPresentationReceived } from '@hyperledger/aries-bifold-verifier';
import { useIsFocused, useNavigation } from '@react-navigation/core';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Linking, Text } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
import { SafeAreaView } from 'react-native-safe-area-context';
import InfoIcon from '../components/buttons/InfoIcon';
import { renderComposer, renderInputToolbar, renderSend } from '../components/chat';
import ActionSlider from '../components/chat/ActionSlider';
import { renderActions } from '../components/chat/ChatActions';
import { ChatEvent } from '../components/chat/ChatEvent';
import { ChatMessage, CallbackType } from '../components/chat/ChatMessage';
import { useNetwork } from '../contexts/network';
import { useStore } from '../contexts/store';
import { useTheme } from '../contexts/theme';
import { useCredentialsByConnectionId } from '../hooks/credentials';
import { useProofsByConnectionId } from '../hooks/proofs';
import { Role } from '../types/chat';
import { BasicMessageMetadata } from '../types/metadata';
import { Screens, Stacks } from '../types/navigators';
import { getConnectionName, getCredentialEventLabel, getCredentialEventRole, getMessageEventRole, getProofEventLabel, getProofEventRole } from '../utils/helpers';
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] = useStore();
  const {
    t
  } = useTranslation();
  const {
    agent
  } = useAgent();
  const navigation = useNavigation();
  const connection = useConnectionById(connectionId);
  const basicMessages = useBasicMessagesByConnectionId(connectionId);
  const credentials = useCredentialsByConnectionId(connectionId);
  const proofs = useProofsByConnectionId(connectionId);
  const isFocused = useIsFocused();
  const {
    assertConnectedNetwork,
    silentAssertConnectedNetwork
  } = useNetwork();
  const [messages, setMessages] = useState([]);
  const [showActionSlider, setShowActionSlider] = useState(false);
  const {
    ChatTheme: theme,
    Assets
  } = useTheme();
  const {
    ColorPallet
  } = useTheme();
  const [theirLabel, setTheirLabel] = useState(getConnectionName(connection, store.preferences.alternateContactNames));

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

  // when chat is open, mark messages as seen
  useEffect(() => {
    basicMessages.forEach(msg => {
      const meta = msg.metadata.get(BasicMessageMetadata.customMetadata);
      if (agent && !(meta !== null && meta !== void 0 && meta.seen)) {
        msg.metadata.set(BasicMessageMetadata.customMetadata, {
          ...meta,
          seen: true
        });
        const basicMessageRepository = agent.context.dependencyManager.resolve(BasicMessageRepository);
        basicMessageRepository.update(agent.context, msg);
      }
    });
  }, [basicMessages]);
  useEffect(() => {
    const transformedMessages = basicMessages.map(record => {
      const role = 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;
        }
        Linking.openURL(link);
      };
      const msgText = /*#__PURE__*/React.createElement(Text, {
        style: role === Role.me ? theme.rightText : theme.leftText
      }, record.content.split(linkRegex).map((split, i) => {
        if (i < links.length) {
          const link = links[i];
          return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Text, null, split), /*#__PURE__*/React.createElement(Text, {
            onPress: () => handleLinkPress(link),
            style: {
              color: ColorPallet.brand.link,
              textDecorationLine: 'underline'
            },
            accessibilityRole: 'link'
          }, link));
        }
        return /*#__PURE__*/React.createElement(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 CredentialExchangeRecord && (record.state === CredentialState.Done || record.state === CredentialState.OfferReceived)) {
        return CallbackType.CredentialOffer;
      }
      if (record instanceof ProofExchangeRecord && isPresentationReceived(record) && record.isVerified !== undefined || record.state === ProofState.RequestReceived || record.state === ProofState.Done && record.isVerified === undefined) {
        return CallbackType.ProofRequest;
      }
      if (record instanceof ProofExchangeRecord && (record.state === ProofState.PresentationSent || record.state === ProofState.Done)) {
        return CallbackType.PresentationSent;
      }
    };
    transformedMessages.push(...credentials.map(record => {
      const role = getCredentialEventRole(record);
      const userLabel = role === Role.me ? t('Chat.UserYou') : theirLabel;
      const actionLabel = t(getCredentialEventLabel(record));
      return {
        _id: record.id,
        text: actionLabel,
        renderEvent: () => /*#__PURE__*/React.createElement(ChatEvent, {
          role: role,
          userLabel: userLabel,
          actionLabel: actionLabel
        }),
        createdAt: record.updatedAt || record.createdAt,
        type: record.type,
        user: {
          _id: role
        },
        messageOpensCallbackType: callbackTypeForMessage(record),
        onDetails: () => {
          const navMap = {
            [CredentialState.Done]: () => {
              navigation.navigate(Stacks.ContactStack, {
                screen: Screens.CredentialDetails,
                params: {
                  credential: record
                }
              });
            },
            [CredentialState.OfferReceived]: () => {
              navigation.navigate(Stacks.ContactStack, {
                screen: Screens.CredentialOffer,
                params: {
                  credentialId: record.id
                }
              });
            }
          };
          const nav = navMap[record.state];
          if (nav) {
            nav();
          }
        }
      };
    }));
    transformedMessages.push(...proofs.map(record => {
      const role = getProofEventRole(record);
      const userLabel = role === Role.me ? t('Chat.UserYou') : theirLabel;
      const actionLabel = t(getProofEventLabel(record));
      return {
        _id: record.id,
        text: actionLabel,
        renderEvent: () => /*#__PURE__*/React.createElement(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(Stacks.ContactStack, {
              screen: Screens.ProofDetails,
              params: {
                recordId: record.id,
                isHistory: true,
                senderReview: record.state === ProofState.PresentationSent || record.state === ProofState.Done && record.isVerified === undefined
              }
            });
          };
          const navMap = {
            [ProofState.Done]: toProofDetails,
            [ProofState.PresentationSent]: toProofDetails,
            [ProofState.PresentationReceived]: toProofDetails,
            [ProofState.RequestReceived]: () => {
              navigation.navigate(Stacks.ContactStack, {
                screen: 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.createElement(Text, {
        style: theme.rightText
      }, t('Chat.YouConnected'), /*#__PURE__*/React.createElement(Text, {
        style: [theme.rightText, theme.rightTextHighlighted]
      }, " ", theirLabel)),
      createdAt: connection.createdAt,
      user: {
        _id: 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 = useCallback(async messages => {
    await (agent === null || agent === void 0 ? void 0 : agent.basicMessages.sendMessage(connectionId, messages[0].text));
  }, [agent, connectionId]);
  const onSendRequest = useCallback(async () => {
    navigation.navigate(Stacks.ProofRequestsStack, {
      screen: Screens.ProofRequests,
      params: {
        navigation: navigation,
        connectionId
      }
    });
  }, [navigation, connectionId]);
  const actions = useMemo(() => {
    return store.preferences.useVerifierCapability ? [{
      text: t('Verifier.SendProofRequest'),
      onPress: () => {
        setShowActionSlider(false);
        onSendRequest();
      },
      icon: () => /*#__PURE__*/React.createElement(Assets.svg.iconInfoSentDark, {
        height: 30,
        width: 30
      })
    }] : undefined;
  }, [t, store.preferences.useVerifierCapability, onSendRequest]);
  const onDismiss = () => {
    setShowActionSlider(false);
  };
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    edges: ['bottom', 'left', 'right'],
    style: {
      flex: 1,
      paddingTop: 20
    }
  }, /*#__PURE__*/React.createElement(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.createElement(ChatMessage, {
      messageProps: props
    }),
    renderInputToolbar: props => renderInputToolbar(props, theme),
    renderSend: props => renderSend(props, theme),
    renderComposer: props => renderComposer(props, theme, t('Contacts.TypeHere')),
    disableComposer: !silentAssertConnectedNetwork(),
    onSend: onSend,
    user: {
      _id: Role.me
    },
    renderActions: props => renderActions(props, theme, actions),
    onPressActionButton: actions ? () => setShowActionSlider(true) : undefined
  }), showActionSlider && /*#__PURE__*/React.createElement(ActionSlider, {
    onDismiss: onDismiss,
    actions: actions
  }));
};
export default Chat;
//# sourceMappingURL=Chat.js.map