'use strict';

var React = require('react');
var index$2 = require('../../index-f65677b1.js');
var Channel_components_SuggestedMentionList = require('./SuggestedMentionList.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var Channel_context = require('../../ChannelProvider-620bb354.js');
var index$1 = require('../../index-f2146bae.js');
var _const = require('../../const-6691e574.js');
var ui_DateSeparator = require('../../ui/DateSeparator.js');
var ui_Label = require('../../index-73643285.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-ab0f6056.js');
var LocalizationContext = require('../../LocalizationContext-af96cf5f.js');
var index = require('../../index-8049c2a3.js');
require('../../index-83d1d15e.js');
require('../../ui/Icon.js');
require('prop-types');
require('../../ui/Avatar.js');
require('../../ui/ImageRenderer.js');
require('../../uuid-0b4ed44c.js');
require('../../ThreadProvider-572574d7.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../UserProfileContext-f068b0ba.js');
require('../../_rollupPluginBabelHelpers-c5955c81.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');
require('../../topics-825e5d42.js');
require('@sendbird/chat/groupChannel');
require('@sendbird/chat/message');
require('../../consts-a5382bc1.js');
require('../../withSendbird.js');
require('../../compareIds-18b3b1d6.js');
require('../../ui/ContextMenu.js');
require('react-dom');
require('../../ui/SortByRow.js');
require('../../stringSet-68748705.js');
require('../../ui/ReactionButton.js');
require('../../color-afeb8dc2.js');
require('../../ui/IconButton.js');
require('../../ui/Button.js');
require('dompurify');
require('../../consts-6ec77e9a.js');
require('../../consts-bc27beff.js');
require('../../consts-a422c2f9.js');
require('../../tokenize-d86ab0c7.js');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../utils-d5176360.js');
require('../../index-900dd19f.js');
require('../../ui/Loader.js');
require('../../index-6cb4a530.js');
require('../../index-4ee95667.js');
require('../../ui/MessageItemMenu.js');
require('../../types-24accb8d.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('../../index-0b344bd7.js');
require('../../index.module-9f5edc7b.js');
require('../../Message/context.js');
require('../../ui/MentionLabel.js');
require('../../ui/LinkLabel.js');
require('../../ui/FileMessageItemBody.js');
require('../../ui/TextButton.js');
require('../../MediaQueryContext-8ec3f647.js');
require('../../ui/ThumbnailMessageItemBody.js');
require('../../ui/OGMessageItemBody.js');
require('../../ui/UnknownMessageItemBody.js');
require('../../ui/QuoteMessage.js');
require('../../useLongPress-d9deb354.js');
require('../../ui/BottomSheet.js');
require('../../index-68c57136.js');
require('../../ui/ThreadReplies.js');
require('../../ui/VoiceMessageItemBody.js');
require('../../ui/ProgressBar.js');
require('../../VoicePlayer/useVoicePlayer.js');
require('../../index-9d518988.js');
require('../../VoiceRecorder/context.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);

const useDidMountEffect = (func, deps) => {
  const [didMount, setDidmount] = React.useState(false);
  React.useEffect(() => {
    if (didMount) {
      func();
    } else {
      setDidmount(true);
    }
  }, deps);
};

// todo: Refactor this component, is too complex now
const Message = _ref => {
  var _message$reactions, _message$isUserMessag;
  let {
    message,
    hasSeparator,
    chainTop,
    chainBottom,
    handleScroll,
    renderCustomSeparator,
    renderEditInput,
    renderMessage,
    renderMessageContent
  } = _ref;
  const {
    dateLocale
  } = LocalizationContext.useLocalization();
  const globalStore = useSendbirdStateContext();
  const {
    userId,
    isOnline,
    isMentionEnabled,
    userMention
  } = globalStore === null || globalStore === void 0 ? void 0 : globalStore.config;
  const maxUserMentionCount = (userMention === null || userMention === void 0 ? void 0 : userMention.maxMentionCount) || _const.MAX_USER_MENTION_COUNT;
  const maxUserSuggestionCount = (userMention === null || userMention === void 0 ? void 0 : userMention.maxSuggestionCount) || _const.MAX_USER_SUGGESTION_COUNT;
  const {
    initialized,
    currentGroupChannel,
    highLightedMessageId,
    setHighLightedMessageId,
    animatedMessageId,
    setAnimatedMessageId,
    updateMessage,
    scrollToMessage,
    replyType,
    threadReplySelectType,
    isReactionEnabled,
    toggleReaction,
    emojiContainer,
    nicknamesMap,
    setQuoteMessage,
    resendMessage,
    renderUserMentionItem,
    onReplyInThread,
    onQuoteMessageClick,
    onMessageAnimated,
    onMessageHighlighted,
    onScrollCallback
  } = Channel_context.useChannelContext();
  const [showEdit, setShowEdit] = React.useState(false);
  const [showRemove, setShowRemove] = React.useState(false);
  const [showFileViewer, setShowFileViewer] = React.useState(false);
  const [isAnimated, setIsAnimated] = React.useState(false);
  const [isHighlighted, setIsHighlighted] = React.useState(false);
  const [mentionNickname, setMentionNickname] = React.useState('');
  const [mentionedUsers, setMentionedUsers] = React.useState([]);
  const [mentionedUserIds, setMentionedUserIds] = React.useState([]);
  const [messageInputEvent, setMessageInputEvent] = React.useState(null);
  const [selectedUser, setSelectedUser] = React.useState(null);
  const [mentionSuggestedUsers, setMentionSuggestedUsers] = React.useState([]);
  const [ableMention, setAbleMention] = React.useState(true);
  const editMessageInputRef = React.useRef(null);
  const messageScrollRef = React.useRef(null);
  const displaySuggestedMentionList = isOnline && isMentionEnabled && mentionNickname.length > 0 && !Channel_context.isDisabledBecauseFrozen(currentGroupChannel) && !Channel_context.isDisabledBecauseMuted(currentGroupChannel);
  const disabled = !initialized || Channel_context.isDisabledBecauseFrozen(currentGroupChannel) || Channel_context.isDisabledBecauseMuted(currentGroupChannel) || !isOnline;
  const handleOnScroll = index.useHandleOnScrollCallback({
    hasMore: false,
    onScroll: onScrollCallback,
    scrollRef: messageScrollRef
  });
  React.useEffect(() => {
    if ((mentionedUsers === null || mentionedUsers === void 0 ? void 0 : mentionedUsers.length) >= maxUserMentionCount) {
      setAbleMention(false);
    } else {
      setAbleMention(true);
    }
  }, [mentionedUsers]);
  React.useEffect(() => {
    setMentionedUsers(mentionedUsers.filter(_ref2 => {
      let {
        userId
      } = _ref2;
      const i = mentionedUserIds.indexOf(userId);
      if (i < 0) {
        return false;
      } else {
        mentionedUserIds.splice(i, 1);
        return true;
      }
    }));
  }, [mentionedUserIds]);

  // Move the messsage list scroll when the last message's height is changed by reactions
  useDidMountEffect(() => {
    var _currentGroupChannel$;
    if ((currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$ = currentGroupChannel.lastMessage) === null || _currentGroupChannel$ === void 0 ? void 0 : _currentGroupChannel$.messageId) === (message === null || message === void 0 ? void 0 : message.messageId)) {
      handleScroll === null || handleScroll === void 0 ? void 0 : handleScroll();
    }
  }, [showEdit, message === null || message === void 0 ? void 0 : (_message$reactions = message.reactions) === null || _message$reactions === void 0 ? void 0 : _message$reactions.length]);
  React.useLayoutEffect(() => {
    let animationTimeout = null;
    let messageHighlightedTimeout = null;
    if (highLightedMessageId === message.messageId && messageScrollRef !== null && messageScrollRef !== void 0 && messageScrollRef.current) {
      handleOnScroll();
      setIsAnimated(false);
      animationTimeout = setTimeout(() => {
        setIsHighlighted(true);
      }, 500);
      messageHighlightedTimeout = setTimeout(() => {
        setHighLightedMessageId(0);
        onMessageHighlighted === null || onMessageHighlighted === void 0 ? void 0 : onMessageHighlighted();
      }, 1600);
    } else {
      setIsHighlighted(false);
    }
    return () => {
      clearTimeout(animationTimeout);
      clearTimeout(messageHighlightedTimeout);
    };
  }, [highLightedMessageId, messageScrollRef.current, message.messageId]);
  React.useLayoutEffect(() => {
    let animationTimeout = null;
    let messageAnimatedTimeout = null;
    if (animatedMessageId === message.messageId && messageScrollRef !== null && messageScrollRef !== void 0 && messageScrollRef.current) {
      handleOnScroll();
      setIsHighlighted(false);
      animationTimeout = setTimeout(() => {
        setIsAnimated(true);
      }, 500);
      messageAnimatedTimeout = setTimeout(() => {
        setAnimatedMessageId(0);
        onMessageAnimated === null || onMessageAnimated === void 0 ? void 0 : onMessageAnimated();
      }, 1600);
    } else {
      setIsAnimated(false);
    }
    return () => {
      clearTimeout(animationTimeout);
      clearTimeout(messageAnimatedTimeout);
    };
  }, [animatedMessageId, messageScrollRef.current, message.messageId, onMessageAnimated]);
  const renderedMessage = React.useMemo(() => {
    return renderMessage === null || renderMessage === void 0 ? void 0 : renderMessage({
      message,
      chainTop,
      chainBottom
    });
  }, [message, renderMessage]);
  const renderedCustomSeparator = React.useMemo(() => {
    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: messageScrollRef,
      className: index$1.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$2.format(message.createdAt, 'MMMM dd, yyyy', {
      locale: dateLocale
    })))), renderedMessage);
  }
  if (showEdit && message !== null && message !== void 0 && (_message$isUserMessag = message.isUserMessage) !== null && _message$isUserMessag !== void 0 && _message$isUserMessag.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: user => {
        if (user) {
          setMentionedUsers([...mentionedUsers, user]);
        }
        setMentionNickname('');
        setSelectedUser(user);
        setMessageInputEvent(null);
      },
      onFocusItemChange: () => {
        setMessageInputEvent(null);
      },
      onFetchUsers: 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: () => {
        var _currentGroupChannel$2;
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$2 = currentGroupChannel.startTyping) === null || _currentGroupChannel$2 === void 0 ? void 0 : _currentGroupChannel$2.call(currentGroupChannel);
      },
      onUpdateMessage: _ref3 => {
        var _currentGroupChannel$3;
        let {
          messageId,
          message,
          mentionTemplate
        } = _ref3;
        updateMessage({
          messageId,
          message,
          mentionedUsers,
          mentionTemplate
        });
        setShowEdit(false);
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$3 = currentGroupChannel.endTyping) === null || _currentGroupChannel$3 === void 0 ? void 0 : _currentGroupChannel$3.call(currentGroupChannel);
      },
      onCancelEdit: () => {
        var _currentGroupChannel$4;
        setMentionNickname('');
        setMentionedUsers([]);
        setMentionedUserIds([]);
        setMentionSuggestedUsers([]);
        setShowEdit(false);
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$4 = currentGroupChannel.endTyping) === null || _currentGroupChannel$4 === void 0 ? void 0 : _currentGroupChannel$4.call(currentGroupChannel);
      },
      onUserMentioned: user => {
        if ((selectedUser === null || selectedUser === void 0 ? void 0 : selectedUser.userId) === (user === null || user === void 0 ? void 0 : user.userId)) {
          setSelectedUser(null);
          setMentionNickname('');
        }
      },
      onMentionStringChange: mentionText => {
        setMentionNickname(mentionText);
      },
      onMentionedUserIdsUpdated: userIds => {
        setMentionedUserIds(userIds);
      },
      onKeyDown: 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$1.getClassName(['sendbird-msg-hoc sendbird-msg--scroll-ref', isAnimated ? 'sendbird-msg-hoc__animated' : '', isHighlighted ? 'sendbird-msg-hoc__highlighted' : '']),
    style: {
      marginBottom: '2px'
    },
    ref: messageScrollRef
  }, 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$2.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,
    onMessageHeightChange: handleScroll
  }), showRemove && /*#__PURE__*/React__default["default"].createElement(Channel_components_RemoveMessageModal, {
    message: message,
    onCancel: () => setShowRemove(false)
  }), showFileViewer && /*#__PURE__*/React__default["default"].createElement(Channel_components_FileViewer["default"], {
    message: message,
    onCancel: () => setShowFileViewer(false)
  }));
};

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