'use strict';

var React = require('react');
var index$2 = require('../../index-358554d2.js');
var Channel_components_SuggestedMentionList = require('./SuggestedMentionList.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var Channel_context = require('../../ChannelProvider-5e48d37b.js');
var index$1 = require('../../index-86e680cb.js');
var _const = require('../../const-f6c8086e.js');
var ui_DateSeparator = require('../../ui/DateSeparator.js');
var ui_Label = require('../../index-bff918b2.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-d9157ccd.js');
var LocalizationContext = require('../../LocalizationContext-6adf6aa8.js');
var index = require('../../index-175b48d7.js');
var useDirtyGetMentions = require('../../useDirtyGetMentions-cef5c0f5.js');
require('../../index-6a7f94de.js');
require('../../ui/Icon.js');
require('prop-types');
require('../../ui/Avatar.js');
require('../../ui/ImageRenderer.js');
require('../../uuid-f1d9be11.js');
require('../../ThreadProvider-593ade0c.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../UserProfileContext-2ff8462c.js');
require('../../_rollupPluginBabelHelpers-ea66c137.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');
require('../../topics-2fe6fef6.js');
require('@sendbird/chat/groupChannel');
require('@sendbird/chat/message');
require('../../consts-a6f34df8.js');
require('../../withSendbird.js');
require('../../compareIds-7b0e4960.js');
require('../../resolvedReplyType-fb851d3a.js');
require('../../color-6641e39b.js');
require('../../stringSet-5157206d.js');
require('../../ui/IconButton.js');
require('../../ui/Button.js');
require('dompurify');
require('../../consts-c7178b6e.js');
require('../../consts-bac93d6f.js');
require('../../consts-3a74400a.js');
require('../../tokenize-bc5f4e11.js');
require('../../index.module-15d2b97f.js');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../utils-58f8eea0.js');
require('../../index-267c66ea.js');
require('../../ui/Loader.js');
require('../../index-e43a902a.js');
require('../../index-66630f40.js');
require('../../ui/MessageItemMenu.js');
require('../../ui/ContextMenu.js');
require('react-dom');
require('../../ui/SortByRow.js');
require('../../types-bed448a4.js');
require('../../ui/MessageItemReactionMenu.js');
require('../../ui/ReactionButton.js');
require('../../useLongPress-928530d4.js');
require('../../MediaQueryContext-1dd78ce3.js');
require('../../ui/EmojiReactions.js');
require('../../ui/ReactionBadge.js');
require('../../ui/BottomSheet.js');
require('../../index-f84d188a.js');
require('../../ui/UserListItem.js');
require('../../ui/MutedAvatarOverlay.js');
require('../../ui/Checkbox.js');
require('../../ui/Tooltip.js');
require('../../ui/TooltipWrapper.js');
require('../../Message/context.js');
require('../../ui/AdminMessage.js');
require('../../ui/TextMessageItemBody.js');
require('../../index-c5341a29.js');
require('../../ui/MentionLabel.js');
require('../../ui/LinkLabel.js');
require('../../ui/FileMessageItemBody.js');
require('../../ui/TextButton.js');
require('../../ui/ThumbnailMessageItemBody.js');
require('../../ui/OGMessageItemBody.js');
require('../../ui/UnknownMessageItemBody.js');
require('../../ui/QuoteMessage.js');
require('../../index-615ae40b.js');
require('../../ui/ThreadReplies.js');
require('../../ui/VoiceMessageItemBody.js');
require('../../ui/ProgressBar.js');
require('../../VoicePlayer/useVoicePlayer.js');
require('../../index-ce276e22.js');
require('../../VoiceRecorder/context.js');
require('../../ui/Modal.js');
require('../../ui/PlaybackTime.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,
    logger
  } = 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 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
  });
  const mentionNodes = useDirtyGetMentions.useDirtyGetMentions({
    ref: editMessageInputRef
  }, {
    logger
  });
  const ableMention = (mentionNodes === null || mentionNodes === void 0 ? void 0 : mentionNodes.length) < maxUserMentionCount;
  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]);
  React.useLayoutEffect(() => {
    // Keep the scrollBottom value after fetching new message list
    handleScroll === null || handleScroll === void 0 ? void 0 : handleScroll();
  }, []);
  /**
   * Move the messsage list scroll
   * when the message's height is changed by `showEdit` OR `message.reactions`
   */
  useDidMountEffect(() => {
    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]);
  useDidMountEffect(() => {
    handleScroll === null || handleScroll === void 0 ? void 0 : handleScroll(true);
  }, [message === null || message === void 0 ? void 0 : message.updatedAt]);
  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", {
      // do not delete this data attribute, used for scroll to given message
      // and also for testing
      "data-sb-message-id": message.messageId,
      "data-sb-created-at": message.createdAt,
      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,
      channel: currentGroupChannel,
      disabled: disabled,
      ref: editMessageInputRef,
      mentionSelectedUser: selectedUser,
      isMentionEnabled: isMentionEnabled,
      message: message,
      onStartTyping: () => {
        var _currentGroupChannel$;
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$ = currentGroupChannel.startTyping) === null || _currentGroupChannel$ === void 0 ? void 0 : _currentGroupChannel$.call(currentGroupChannel);
      },
      onUpdateMessage: _ref3 => {
        var _currentGroupChannel$2;
        let {
          messageId,
          message,
          mentionTemplate
        } = _ref3;
        updateMessage({
          messageId,
          message,
          mentionedUsers,
          mentionTemplate
        });
        setShowEdit(false);
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$2 = currentGroupChannel.endTyping) === null || _currentGroupChannel$2 === void 0 ? void 0 : _currentGroupChannel$2.call(currentGroupChannel);
      },
      onCancelEdit: () => {
        var _currentGroupChannel$3;
        setMentionNickname('');
        setMentionedUsers([]);
        setMentionedUserIds([]);
        setMentionSuggestedUsers([]);
        setShowEdit(false);
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$3 = currentGroupChannel.endTyping) === null || _currentGroupChannel$3 === void 0 ? void 0 : _currentGroupChannel$3.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'
    },
    "data-sb-message-id": message.messageId,
    "data-sb-created-at": message.createdAt,
    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
