'use strict';

var tslib_es6 = require('../../tslib.es6-d2ba1a6b.js');
var React = require('react');
var index$1 = require('../../index-81e19961.js');
var Channel_components_SuggestedMentionList = require('./SuggestedMentionList.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var Channel_context = require('../../ChannelProvider-b1290e55.js');
var index = require('../../index-b32fce67.js');
var _const = require('../../const-77194948.js');
var ui_DateSeparator = require('../../ui/DateSeparator.js');
var ui_Label = require('../../index-1b11bb85.js');
var ui_MessageInput = require('../../ui/MessageInput.js');
var ui_MessageContent = require('../../ui/MessageContent.js');
var Channel_components_FileViewer = require('./FileViewer.js');
var Channel_components_RemoveMessageModal = require('./RemoveMessageModal.js');
var _const$1 = require('../../const-fe838b59.js');
var LocalizationContext = require('../../LocalizationContext-1f669b3c.js');
require('../../index-f5502150.js');
require('../../ui/Icon.js');
require('prop-types');
require('../../ui/Avatar.js');
require('../../ui/ImageRenderer.js');
require('../../uuid-28e4a814.js');
require('../../ThreadProvider-5eafb9ef.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../UserProfileContext-cde95db8.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');
require('../../topics-5edbb1b2.js');
require('@sendbird/chat/groupChannel');
require('@sendbird/chat/message');
require('../../consts-f82aaae9.js');
require('../../withSendbird.js');
require('../../_rollupPluginBabelHelpers-32557b21.js');
require('../../compareIds-32f97a73.js');
require('../../ui/ContextMenu.js');
require('react-dom');
require('../../ui/SortByRow.js');
require('../../stringSet-ddd351f0.js');
require('../../ui/ReactionButton.js');
require('../../color-97cfc61b.js');
require('react-dom/server');
require('../../ui/IconButton.js');
require('../../ui/Button.js');
require('../../ui/MentionUserLabel.js');
require('dompurify');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../utils-602ab2fc.js');
require('../../index-b911f8b3.js');
require('../../ui/Loader.js');
require('../../index-c4869cdb.js');
require('../../index-78e2bb42.js');
require('../../ui/MessageItemMenu.js');
require('../../types-3fb94919.js');
require('../../ui/MessageItemReactionMenu.js');
require('../../ui/EmojiReactions.js');
require('../../ui/Tooltip.js');
require('../../ui/TooltipWrapper.js');
require('../../ui/ReactionBadge.js');
require('../../ui/AdminMessage.js');
require('../../ui/TextMessageItemBody.js');
require('../../ui/Word.js');
require('../../ui/LinkLabel.js');
require('../../ui/MentionLabel.js');
require('../../ui/FileMessageItemBody.js');
require('../../ui/TextButton.js');
require('../../MediaQueryContext-130143d7.js');
require('../../ui/ThumbnailMessageItemBody.js');
require('../../ui/OGMessageItemBody.js');
require('../../ui/UnknownMessageItemBody.js');
require('../../ui/QuoteMessage.js');
require('../../useLongPress-778d6f15.js');
require('../../ui/BottomSheet.js');
require('../../index-577c9a9b.js');
require('../../ui/ThreadReplies.js');
require('../../ui/VoiceMessageItemBody.js');
require('../../ui/ProgressBar.js');
require('../../VoicePlayer/useVoicePlayer.js');
require('../../index-26ff28a8.js');
require('../../VoiceRecorder/context.js');
require('../../lame.all.js');
require('../../ui/PlaybackTime.js');
require('../../ui/Modal.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

var useDidMountEffect = function (func, deps) {
  var _a = React.useState(false),
      didMount = _a[0],
      setDidmount = _a[1];

  React.useEffect(function () {
    if (didMount) {
      func();
    } else {
      setDidmount(true);
    }
  }, deps);
};

var Message = function (_a) {
  var _b, _c;

  var message = _a.message,
      hasSeparator = _a.hasSeparator,
      chainTop = _a.chainTop,
      chainBottom = _a.chainBottom,
      handleScroll = _a.handleScroll,
      renderCustomSeparator = _a.renderCustomSeparator,
      renderEditInput = _a.renderEditInput,
      renderMessage = _a.renderMessage,
      renderMessageContent = _a.renderMessageContent;
  var dateLocale = LocalizationContext.useLocalization().dateLocale;
  var globalStore = useSendbirdStateContext();

  var _d = globalStore === null || globalStore === void 0 ? void 0 : globalStore.config,
      userId = _d.userId,
      isOnline = _d.isOnline,
      isMentionEnabled = _d.isMentionEnabled,
      userMention = _d.userMention;

  var maxUserMentionCount = (userMention === null || userMention === void 0 ? void 0 : userMention.maxMentionCount) || _const.MAX_USER_MENTION_COUNT;
  var maxUserSuggestionCount = (userMention === null || userMention === void 0 ? void 0 : userMention.maxSuggestionCount) || _const.MAX_USER_SUGGESTION_COUNT;

  var _e = Channel_context.useChannelContext(),
      initialized = _e.initialized,
      currentGroupChannel = _e.currentGroupChannel,
      highLightedMessageId = _e.highLightedMessageId,
      setHighLightedMessageId = _e.setHighLightedMessageId,
      animatedMessageId = _e.animatedMessageId,
      setAnimatedMessageId = _e.setAnimatedMessageId,
      updateMessage = _e.updateMessage,
      scrollToMessage = _e.scrollToMessage,
      replyType = _e.replyType,
      threadReplySelectType = _e.threadReplySelectType,
      isReactionEnabled = _e.isReactionEnabled,
      toggleReaction = _e.toggleReaction,
      emojiContainer = _e.emojiContainer,
      nicknamesMap = _e.nicknamesMap,
      setQuoteMessage = _e.setQuoteMessage,
      resendMessage = _e.resendMessage,
      renderUserMentionItem = _e.renderUserMentionItem,
      onReplyInThread = _e.onReplyInThread,
      onQuoteMessageClick = _e.onQuoteMessageClick,
      onMessageAnimated = _e.onMessageAnimated,
      onMessageHighlighted = _e.onMessageHighlighted;

  var _f = React.useState(false),
      showEdit = _f[0],
      setShowEdit = _f[1];

  var _g = React.useState(false),
      showRemove = _g[0],
      setShowRemove = _g[1];

  var _h = React.useState(false),
      showFileViewer = _h[0],
      setShowFileViewer = _h[1];

  var _j = React.useState(false),
      isAnimated = _j[0],
      setIsAnimated = _j[1];

  var _k = React.useState(false),
      isHighlighted = _k[0],
      setIsHighlighted = _k[1];

  var _l = React.useState(''),
      mentionNickname = _l[0],
      setMentionNickname = _l[1];

  var _m = React.useState([]),
      mentionedUsers = _m[0],
      setMentionedUsers = _m[1];

  var _o = React.useState([]),
      mentionedUserIds = _o[0],
      setMentionedUserIds = _o[1];

  var _p = React.useState(null),
      messageInputEvent = _p[0],
      setMessageInputEvent = _p[1];

  var _q = React.useState(null),
      selectedUser = _q[0],
      setSelectedUser = _q[1];

  var _r = React.useState([]),
      mentionSuggestedUsers = _r[0],
      setMentionSuggestedUsers = _r[1];

  var _s = React.useState(true),
      ableMention = _s[0],
      setAbleMention = _s[1];

  var editMessageInputRef = React.useRef(null);
  var useMessageScrollRef = React.useRef(null);
  var displaySuggestedMentionList = isOnline && isMentionEnabled && mentionNickname.length > 0 && !Channel_context.isDisabledBecauseFrozen(currentGroupChannel) && !Channel_context.isDisabledBecauseMuted(currentGroupChannel);
  var disabled = !initialized || Channel_context.isDisabledBecauseFrozen(currentGroupChannel) || Channel_context.isDisabledBecauseMuted(currentGroupChannel) || !isOnline;
  React.useEffect(function () {
    if ((mentionedUsers === null || mentionedUsers === void 0 ? void 0 : mentionedUsers.length) >= maxUserMentionCount) {
      setAbleMention(false);
    } else {
      setAbleMention(true);
    }
  }, [mentionedUsers]);
  React.useEffect(function () {
    setMentionedUsers(mentionedUsers.filter(function (_a) {
      var userId = _a.userId;
      var i = mentionedUserIds.indexOf(userId);

      if (i < 0) {
        return false;
      } else {
        mentionedUserIds.splice(i, 1);
        return true;
      }
    }));
  }, [mentionedUserIds]);
  useDidMountEffect(function () {
    var _a;

    if (((_a = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.lastMessage) === null || _a === void 0 ? void 0 : _a.messageId) === (message === null || message === void 0 ? void 0 : message.messageId)) {
      handleScroll === null || handleScroll === void 0 ? void 0 : handleScroll();
    }
  }, [showEdit, (_b = message === null || message === void 0 ? void 0 : message.reactions) === null || _b === void 0 ? void 0 : _b.length]);
  React.useLayoutEffect(function () {
    var animationTimeout = null;
    var messageHighlightedTimeout = null;

    if (highLightedMessageId === message.messageId && (useMessageScrollRef === null || useMessageScrollRef === void 0 ? void 0 : useMessageScrollRef.current)) {
      useMessageScrollRef.current.scrollIntoView({
        block: 'center',
        inline: 'center'
      });
      setIsAnimated(false);
      animationTimeout = setTimeout(function () {
        setIsHighlighted(true);
      }, 500);
      messageHighlightedTimeout = setTimeout(function () {
        setHighLightedMessageId(0);
        onMessageHighlighted === null || onMessageHighlighted === void 0 ? void 0 : onMessageHighlighted();
      }, 1600);
    } else {
      setIsHighlighted(false);
    }

    return function () {
      clearTimeout(animationTimeout);
      clearTimeout(messageHighlightedTimeout);
    };
  }, [highLightedMessageId, useMessageScrollRef.current, message.messageId]);
  React.useLayoutEffect(function () {
    var animationTimeout = null;
    var messageAnimatedTimeout = null;

    if (animatedMessageId === message.messageId && (useMessageScrollRef === null || useMessageScrollRef === void 0 ? void 0 : useMessageScrollRef.current)) {
      useMessageScrollRef.current.scrollIntoView({
        block: 'center',
        inline: 'center'
      });
      setIsHighlighted(false);
      animationTimeout = setTimeout(function () {
        setIsAnimated(true);
      }, 500);
      messageAnimatedTimeout = setTimeout(function () {
        setAnimatedMessageId(0);
        onMessageAnimated === null || onMessageAnimated === void 0 ? void 0 : onMessageAnimated();
      }, 1600);
    } else {
      setIsAnimated(false);
    }

    return function () {
      clearTimeout(animationTimeout);
      clearTimeout(messageAnimatedTimeout);
    };
  }, [animatedMessageId, useMessageScrollRef.current, message.messageId, onMessageAnimated]);
  var renderedMessage = React.useMemo(function () {
    return renderMessage === null || renderMessage === void 0 ? void 0 : renderMessage({
      message: message,
      chainTop: chainTop,
      chainBottom: chainBottom
    });
  }, [message, renderMessage]);
  var renderedCustomSeparator = React.useMemo(function () {
    if (renderCustomSeparator) {
      return renderCustomSeparator === null || renderCustomSeparator === void 0 ? void 0 : renderCustomSeparator({
        message: message
      });
    }

    return null;
  }, [message, renderCustomSeparator]);

  if (renderedMessage) {
    return /*#__PURE__*/React__default["default"].createElement("div", {
      ref: useMessageScrollRef,
      className: index.getClassName(['sendbird-msg-hoc sendbird-msg--scroll-ref', isAnimated ? 'sendbird-msg-hoc__animated' : '', isHighlighted ? 'sendbird-msg-hoc__highlighted' : ''])
    }, // TODO: Add message instance as a function parameter
    hasSeparator && (renderedCustomSeparator || /*#__PURE__*/React__default["default"].createElement(ui_DateSeparator, null, /*#__PURE__*/React__default["default"].createElement(ui_Label.Label, {
      type: ui_Label.LabelTypography.CAPTION_2,
      color: ui_Label.LabelColors.ONBACKGROUND_2
    }, index$1.format(message.createdAt, 'MMMM dd, yyyy', {
      locale: dateLocale
    })))), renderedMessage);
  }

  if (showEdit && ((_c = message === null || message === void 0 ? void 0 : message.isUserMessage) === null || _c === void 0 ? void 0 : _c.call(message))) {
    return (renderEditInput === null || renderEditInput === void 0 ? void 0 : renderEditInput()) || /*#__PURE__*/React__default["default"].createElement(React__default["default"].Fragment, null, displaySuggestedMentionList && /*#__PURE__*/React__default["default"].createElement(Channel_components_SuggestedMentionList, {
      targetNickname: mentionNickname,
      inputEvent: messageInputEvent,
      renderUserMentionItem: renderUserMentionItem,
      onUserItemClick: function (user) {
        if (user) {
          setMentionedUsers(tslib_es6.__spreadArray(tslib_es6.__spreadArray([], mentionedUsers, true), [user], false));
        }

        setMentionNickname('');
        setSelectedUser(user);
        setMessageInputEvent(null);
      },
      onFocusItemChange: function () {
        setMessageInputEvent(null);
      },
      onFetchUsers: function (users) {
        setMentionSuggestedUsers(users);
      },
      ableAddMention: ableMention,
      maxMentionCount: maxUserMentionCount,
      maxSuggestionCount: maxUserSuggestionCount
    }), /*#__PURE__*/React__default["default"].createElement(ui_MessageInput, {
      isEdit: true,
      disabled: disabled,
      ref: editMessageInputRef,
      mentionSelectedUser: selectedUser,
      isMentionEnabled: isMentionEnabled,
      message: message,
      onStartTyping: function () {
        var _a;

        (_a = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.startTyping) === null || _a === void 0 ? void 0 : _a.call(currentGroupChannel);
      },
      onUpdateMessage: function (_a) {
        var _b;

        var messageId = _a.messageId,
            message = _a.message,
            mentionTemplate = _a.mentionTemplate;
        updateMessage({
          messageId: messageId,
          message: message,
          mentionedUsers: mentionedUsers,
          mentionTemplate: mentionTemplate
        });
        setShowEdit(false);
        (_b = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.endTyping) === null || _b === void 0 ? void 0 : _b.call(currentGroupChannel);
      },
      onCancelEdit: function () {
        var _a;

        setMentionNickname('');
        setMentionedUsers([]);
        setMentionedUserIds([]);
        setMentionSuggestedUsers([]);
        setShowEdit(false);
        (_a = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.endTyping) === null || _a === void 0 ? void 0 : _a.call(currentGroupChannel);
      },
      onUserMentioned: function (user) {
        if ((selectedUser === null || selectedUser === void 0 ? void 0 : selectedUser.userId) === (user === null || user === void 0 ? void 0 : user.userId)) {
          setSelectedUser(null);
          setMentionNickname('');
        }
      },
      onMentionStringChange: function (mentionText) {
        setMentionNickname(mentionText);
      },
      onMentionedUserIdsUpdated: function (userIds) {
        setMentionedUserIds(userIds);
      },
      onKeyDown: function (e) {
        if (displaySuggestedMentionList && (mentionSuggestedUsers === null || mentionSuggestedUsers === void 0 ? void 0 : mentionSuggestedUsers.length) > 0 && (e.key === _const$1.MessageInputKeys.Enter && ableMention || e.key === _const$1.MessageInputKeys.ArrowUp || e.key === _const$1.MessageInputKeys.ArrowDown)) {
          setMessageInputEvent(e);
          return true;
        }

        return false;
      }
    }));
  }

  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: index.getClassName(['sendbird-msg-hoc sendbird-msg--scroll-ref', isAnimated ? 'sendbird-msg-hoc__animated' : '', isHighlighted ? 'sendbird-msg-hoc__highlighted' : '']),
    style: {
      marginBottom: '2px'
    },
    ref: useMessageScrollRef
  }, hasSeparator && (renderedCustomSeparator || /*#__PURE__*/React__default["default"].createElement(ui_DateSeparator, null, /*#__PURE__*/React__default["default"].createElement(ui_Label.Label, {
    type: ui_Label.LabelTypography.CAPTION_2,
    color: ui_Label.LabelColors.ONBACKGROUND_2
  }, index$1.format(message.createdAt, 'MMMM dd, yyyy', {
    locale: dateLocale
  })))), (renderMessageContent === null || renderMessageContent === void 0 ? void 0 : renderMessageContent()) || /*#__PURE__*/React__default["default"].createElement(ui_MessageContent, {
    className: "sendbird-message-hoc__message-content",
    userId: userId,
    scrollToMessage: scrollToMessage,
    channel: currentGroupChannel,
    message: message,
    disabled: !isOnline,
    chainTop: chainTop,
    chainBottom: chainBottom,
    isReactionEnabled: isReactionEnabled,
    replyType: replyType,
    threadReplySelectType: threadReplySelectType,
    nicknamesMap: nicknamesMap,
    emojiContainer: emojiContainer,
    showEdit: setShowEdit,
    showRemove: setShowRemove,
    showFileViewer: setShowFileViewer,
    resendMessage: resendMessage,
    toggleReaction: toggleReaction,
    setQuoteMessage: setQuoteMessage,
    onReplyInThread: onReplyInThread,
    onQuoteMessageClick: onQuoteMessageClick
  }), showRemove && /*#__PURE__*/React__default["default"].createElement(Channel_components_RemoveMessageModal, {
    message: message,
    onCancel: function () {
      return setShowRemove(false);
    }
  }), showFileViewer && /*#__PURE__*/React__default["default"].createElement(Channel_components_FileViewer["default"], {
    message: message,
    onCancel: function () {
      return setShowFileViewer(false);
    }
  }));
};

module.exports = Message;
//# sourceMappingURL=Message.js.map
