'use strict';

var React = require('react');
var Channel_context = require('../../ChannelProvider-620bb354.js');
var ui_PlaceHolder = require('../../index-ff8ea47f.js');
var ui_Icon = require('../../ui/Icon.js');
var Channel_components_Message = require('./Message.js');
var index = require('../../index-4ee95667.js');
var Channel_components_UnreadCount = require('./UnreadCount.js');
var Channel_components_FrozenNotification = require('./FrozenNotification.js');
var consts = require('../../consts-a5382bc1.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var Message_context = require('../../Message/context.js');
var index$1 = require('../../index-8049c2a3.js');
require('../../UserProfileContext-f068b0ba.js');
require('prop-types');
require('../../index-f65677b1.js');
require('../../index-83d1d15e.js');
require('../../topics-825e5d42.js');
require('../../index-f2146bae.js');
require('../../_rollupPluginBabelHelpers-c5955c81.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../compareIds-18b3b1d6.js');
require('../../const-6691e574.js');
require('@sendbird/chat/groupChannel');
require('../../uuid-0b4ed44c.js');
require('@sendbird/chat/message');
require('../../ui/ContextMenu.js');
require('react-dom');
require('../../ui/SortByRow.js');
require('../../index-73643285.js');
require('../../stringSet-68748705.js');
require('../../ui/ReactionButton.js');
require('../../ui/ImageRenderer.js');
require('../../LocalizationContext-af96cf5f.js');
require('../../ui/Loader.js');
require('./SuggestedMentionList.js');
require('../../ui/Avatar.js');
require('../../const-ab0f6056.js');
require('../../ThreadProvider-572574d7.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');
require('../../ui/DateSeparator.js');
require('../../color-afeb8dc2.js');
require('../../ui/MessageInput.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/MessageContent.js');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../utils-d5176360.js');
require('../../index-900dd19f.js');
require('../../index-6cb4a530.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('../../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('../../withSendbird.js');
require('../../ui/PlaybackTime.js');
require('./FileViewer.js');
require('./RemoveMessageModal.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 getMessagePartsInfo = _ref => {
  let {
    allMessages = [],
    isMessageGroupingEnabled = true,
    currentIndex = 0,
    currentMessage = null,
    currentChannel = null,
    replyType = ''
  } = _ref;
  const previousMessage = allMessages[currentIndex - 1];
  const nextMessage = allMessages[currentIndex + 1];
  const [chainTop, chainBottom] = isMessageGroupingEnabled ? Channel_context.compareMessagesForGrouping(previousMessage, currentMessage, nextMessage, currentChannel, replyType) : [false, false];
  const previousMessageCreatedAt = previousMessage === null || previousMessage === void 0 ? void 0 : previousMessage.createdAt;
  const currentCreatedAt = currentMessage.createdAt;
  // https://stackoverflow.com/a/41855608
  const hasSeparator = !(previousMessageCreatedAt && index.isSameDay(currentCreatedAt, previousMessageCreatedAt));
  return {
    chainTop,
    chainBottom,
    hasSeparator
  };
};

const MessageList = _ref => {
  let {
    className = '',
    renderMessage,
    renderPlaceholderEmpty,
    renderCustomSeparator,
    renderPlaceholderLoader
  } = _ref;
  const {
    allMessages,
    hasMorePrev,
    setInitialTimeStamp,
    setAnimatedMessageId,
    setHighLightedMessageId,
    isMessageGroupingEnabled,
    scrollRef,
    onScrollDownCallback,
    messagesDispatcher,
    messageActionTypes,
    currentGroupChannel,
    disableMarkAsRead,
    filterMessageList,
    replyType,
    loading,
    unreadSince
  } = Channel_context.useChannelContext();
  const store = useSendbirdStateContext();
  const [scrollBottom, setScrollBottom] = React.useState(0);
  const allMessagesFiltered = typeof filterMessageList === 'function' ? allMessages.filter(filterMessageList) : allMessages;
  const markAsReadScheduler = store.config.markAsReadScheduler;
  const onScroll = () => {
    const element = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
    if (element == null) {
      return;
    }
    const {
      scrollTop,
      clientHeight,
      scrollHeight
    } = element;
    if (Channel_context.isAboutSame(clientHeight + scrollTop, scrollHeight, consts.SCROLL_BUFFER)) {
      onScrollDownCallback(_ref2 => {
      });
    }

    // Save the lastest scroll bottom value
    setScrollBottom(element.scrollHeight - element.scrollTop - element.offsetHeight);
    if (!disableMarkAsRead && Channel_context.isAboutSame(clientHeight + scrollTop, scrollHeight, consts.SCROLL_BUFFER)) {
      messagesDispatcher({
        type: messageActionTypes.MARK_AS_READ,
        payload: {
          channel: currentGroupChannel
        }
      });
      markAsReadScheduler === null || markAsReadScheduler === void 0 ? void 0 : markAsReadScheduler.push(currentGroupChannel);
    }
  };
  const onClickScrollBot = () => {
    var _scrollRef$current;
    setInitialTimeStamp === null || setInitialTimeStamp === void 0 ? void 0 : setInitialTimeStamp(null);
    setAnimatedMessageId === null || setAnimatedMessageId === void 0 ? void 0 : setAnimatedMessageId(null);
    setHighLightedMessageId === null || setHighLightedMessageId === void 0 ? void 0 : setHighLightedMessageId(null);
    if ((scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current = scrollRef.current) === null || _scrollRef$current === void 0 ? void 0 : _scrollRef$current.scrollTop) > -1) {
      var _scrollRef$current2, _scrollRef$current3;
      scrollRef.current.scrollTop = (scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current2 = scrollRef.current) === null || _scrollRef$current2 === void 0 ? void 0 : _scrollRef$current2.scrollHeight) - (scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current3 = scrollRef.current) === null || _scrollRef$current3 === void 0 ? void 0 : _scrollRef$current3.offsetHeight);
    }
  };
  const handleMessageHeightChange = () => {
    const current = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
    if (current) {
      const bottom = current.scrollHeight - current.scrollTop - current.offsetHeight;
      if (scrollBottom < bottom && scrollBottom <= consts.SCROLL_BUFFER) {
        current.scrollTop += bottom - scrollBottom;
      }
    }
  };
  const handleOnScroll = index$1.useHandleOnScrollCallback({
    hasMore: hasMorePrev,
    onScroll,
    scrollRef
  });
  if (loading) {
    return typeof renderPlaceholderLoader === 'function' ? renderPlaceholderLoader() : /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
      type: ui_PlaceHolder.PlaceHolderTypes.LOADING
    });
  }
  if (allMessagesFiltered.length < 1) {
    if (renderPlaceholderEmpty && typeof renderPlaceholderEmpty === 'function') {
      return renderPlaceholderEmpty();
    }
    return /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
      className: "sendbird-conversation__no-messages",
      type: ui_PlaceHolder.PlaceHolderTypes.NO_MESSAGES
    });
  }
  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: `sendbird-conversation__messages ${className}`
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__scroll-container"
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__padding"
  }), /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__messages-padding",
    ref: scrollRef,
    onScroll: handleOnScroll
  }, allMessagesFiltered.map((m, idx) => {
    var _sender, _store$config;
    const {
      chainTop,
      chainBottom,
      hasSeparator
    } = getMessagePartsInfo({
      allMessages: allMessagesFiltered,
      replyType,
      isMessageGroupingEnabled,
      currentIndex: idx,
      currentMessage: m,
      currentChannel: currentGroupChannel
    });
    const isByMe = (m === null || m === void 0 ? void 0 : (_sender = m.sender) === null || _sender === void 0 ? void 0 : _sender.userId) === (store === null || store === void 0 ? void 0 : (_store$config = store.config) === null || _store$config === void 0 ? void 0 : _store$config.userId);
    return /*#__PURE__*/React__default["default"].createElement(Message_context.MessageProvider, {
      message: m,
      key: m === null || m === void 0 ? void 0 : m.messageId,
      isByMe: isByMe
    }, /*#__PURE__*/React__default["default"].createElement(Channel_components_Message, {
      handleScroll: handleMessageHeightChange,
      renderMessage: renderMessage,
      message: m,
      hasSeparator: hasSeparator,
      chainTop: chainTop,
      chainBottom: chainBottom,
      renderCustomSeparator: renderCustomSeparator
    }));
  }))), (currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.isFrozen) && /*#__PURE__*/React__default["default"].createElement(Channel_components_FrozenNotification, {
    className: "sendbird-conversation__messages__notification"
  }), /*#__PURE__*/React__default["default"].createElement(Channel_components_UnreadCount, {
    className: "sendbird-conversation__messages__notification",
    count: currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.unreadMessageCount,
    time: unreadSince,
    onClick: () => {
      var _scrollRef$current4;
      if (scrollRef !== null && scrollRef !== void 0 && (_scrollRef$current4 = scrollRef.current) !== null && _scrollRef$current4 !== void 0 && _scrollRef$current4.scrollTop) {
        var _scrollRef$current5, _scrollRef$current6;
        scrollRef.current.scrollTop = (scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current5 = scrollRef.current) === null || _scrollRef$current5 === void 0 ? void 0 : _scrollRef$current5.scrollHeight) - (scrollRef === null || scrollRef === void 0 ? void 0 : (_scrollRef$current6 = scrollRef.current) === null || _scrollRef$current6 === void 0 ? void 0 : _scrollRef$current6.offsetHeight);
      }
      if (!disableMarkAsRead) {
        markAsReadScheduler === null || markAsReadScheduler === void 0 ? void 0 : markAsReadScheduler.push(currentGroupChannel);
        messagesDispatcher({
          type: messageActionTypes.MARK_AS_READ,
          payload: {
            channel: currentGroupChannel
          }
        });
      }
      setInitialTimeStamp(null);
      setAnimatedMessageId(null);
      setHighLightedMessageId(null);
    }
  }),
  // This flag is an unmatched variable
  scrollBottom > 1 && /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__scroll-bottom-button",
    onClick: onClickScrollBot,
    onKeyDown: onClickScrollBot,
    tabIndex: 0,
    role: "button"
  }, /*#__PURE__*/React__default["default"].createElement(ui_Icon["default"], {
    width: "24px",
    height: "24px",
    type: ui_Icon.IconTypes.CHEVRON_DOWN,
    fillColor: ui_Icon.IconColors.PRIMARY
  })));
};

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