'use strict';

var React = require('react');
var ChannelList_components_ChannelListHeader = require('./ChannelListHeader.js');
var ChannelList_components_AddChannel = require('./AddChannel.js');
var ChannelList_components_ChannelPreview = require('./ChannelPreview.js');
var ChannelList_components_ChannelPreviewAction = require('./ChannelPreviewAction.js');
var ChannelList_context = require('../../ChannelListProvider-6278e465.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var EditUserProfile = require('../../EditUserProfile.js');
var ui_PlaceHolder = require('../../index-9a5e4383.js');
require('../../LocalizationContext-44d2f61b.js');
require('../../stringSet-7aebf034.js');
require('../../index-88e8fdfa.js');
require('../../index-2bfd366f.js');
require('prop-types');
require('../../ui/Avatar.js');
require('../../ui/ImageRenderer.js');
require('../../ui/Icon.js');
require('../../uuid-dee74248.js');
require('../../ui/IconButton.js');
require('../../_rollupPluginBabelHelpers-21ae158b.js');
require('../../CreateChannel.js');
require('../../CreateChannel/components/CreateChannelUI.js');
require('../../CreateChannelProvider-2e0d0496.js');
require('../../sendbirdSelectors.js');
require('../../topics-373d2156.js');
require('../../utils-6a748c02.js');
require('../../CreateChannel/components/InviteUsers.js');
require('../../ui/Modal.js');
require('react-dom');
require('../../index-0a446cca.js');
require('../../ui/Button.js');
require('../../MediaQueryContext-5d311a86.js');
require('../../ui/UserListItem.js');
require('../../UserProfileContext-9d843d68.js');
require('../../ui/MutedAvatarOverlay.js');
require('../../ui/Checkbox.js');
require('../../ui/UserProfile.js');
require('../../ui/ContextMenu.js');
require('../../ui/SortByRow.js');
require('../../index-1b3c69da.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../CreateChannel/components/SelectChannelType.js');
require('../../ui/ChannelAvatar.js');
require('../../utils-c71f0bea.js');
require('../../ui/Badge.js');
require('../../index-b6657c80.js');
require('../../index-892b4b7f.js');
require('../../ui/Loader.js');
require('../../index-24f791d1.js');
require('../../index-a3268370.js');
require('../../ui/MentionUserLabel.js');
require('../../consts-867f1ae6.js');
require('../../ui/TextButton.js');
require('../../color-0c04efbd.js');
require('../../Channel/components/TypingIndicator.js');
require('@sendbird/chat/groupChannel');
require('../../ChannelProvider-a05d259f.js');
require('../../const-1ea78727.js');
require('../../compareIds-a846891d.js');
require('@sendbird/chat/message');
require('../../consts-900e72b9.js');
require('../../resolvedReplyType-14fa0f85.js');
require('../../useLongPress-83b6a2f1.js');
require('../../withSendbird.js');
require('../../index-77d10148.js');
require('../../ui/Input.js');
require('../../actionTypes-944c8755.js');

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

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

const isAboutSame = (a, b, px) => Math.abs(a - b) <= px;

const DELIVERY_RECIPT = 'delivery_receipt';
const ChannelListUI = props => {
  var _state$stores;
  const {
    renderHeader,
    renderChannelPreview,
    renderPlaceHolderError,
    renderPlaceHolderLoading,
    renderPlaceHolderEmptyList
  } = props;
  const [showProfileEdit, setShowProfileEdit] = React.useState(false);
  const {
    onThemeChange,
    allowProfileEdit,
    allChannels,
    loading,
    currentChannel,
    channelListDispatcher,
    channelSource,
    typingChannels,
    initialized
  } = ChannelList_context.useChannelListContext();
  const state = useSendbirdStateContext();
  const sdkStore = state === null || state === void 0 ? void 0 : (_state$stores = state.stores) === null || _state$stores === void 0 ? void 0 : _state$stores.sdkStore;
  const config = state === null || state === void 0 ? void 0 : state.config;
  const {
    logger,
    isOnline = false,
    markAsDeliveredScheduler,
    disableMarkAsDelivered
  } = config;
  const sdk = sdkStore === null || sdkStore === void 0 ? void 0 : sdkStore.sdk;
  const sdkError = sdkStore === null || sdkStore === void 0 ? void 0 : sdkStore.error;
  return /*#__PURE__*/React__default["default"].createElement(React__default["default"].Fragment, null, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-channel-list__header"
  }, (renderHeader === null || renderHeader === void 0 ? void 0 : renderHeader()) || /*#__PURE__*/React__default["default"].createElement(ChannelList_components_ChannelListHeader, {
    onEdit: () => {
      if (allowProfileEdit) {
        setShowProfileEdit(true);
      }
    },
    allowProfileEdit: allowProfileEdit,
    renderIconButton: () => /*#__PURE__*/React__default["default"].createElement(ChannelList_components_AddChannel.AddChannel, null)
  })), showProfileEdit && /*#__PURE__*/React__default["default"].createElement(EditUserProfile, {
    onThemeChange: onThemeChange,
    onCancel: () => {
      setShowProfileEdit(false);
    },
    onEditProfile: () => {
      setShowProfileEdit(false);
    }
  }), /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-channel-list__body",
    onScroll: e => {
      const target = e === null || e === void 0 ? void 0 : e.target;
      const fetchMore = isAboutSame(target.clientHeight + target.scrollTop, target.scrollHeight, 10);
      if (fetchMore && channelSource !== null && channelSource !== void 0 && channelSource.hasNext) {
        logger.info('ChannelList: Fetching more channels');
        channelListDispatcher({
          type: ChannelList_context.FETCH_CHANNELS_START,
          payload: null
        });
        channelSource.next().then(channelList => {
          var _sdk$appInfo, _sdk$appInfo$premiumF;
          logger.info('ChannelList: Fetching channels successful', channelList);
          channelListDispatcher({
            type: ChannelList_context.FETCH_CHANNELS_SUCCESS,
            payload: channelList
          });
          const canSetMarkAsDelivered = sdk === null || sdk === void 0 ? void 0 : (_sdk$appInfo = sdk.appInfo) === null || _sdk$appInfo === void 0 ? void 0 : (_sdk$appInfo$premiumF = _sdk$appInfo.premiumFeatureList) === null || _sdk$appInfo$premiumF === void 0 ? void 0 : _sdk$appInfo$premiumF.find(feature => feature === DELIVERY_RECIPT);
          if (canSetMarkAsDelivered && !disableMarkAsDelivered) {
            logger.info('ChannelList: Marking all channels as read');
            // eslint-disable-next-line no-unused-expressions
            channelList === null || channelList === void 0 ? void 0 : channelList.forEach(channel => {
              if ((channel === null || channel === void 0 ? void 0 : channel.unreadMessageCount) > 0) {
                markAsDeliveredScheduler.push(channel);
              }
            });
          }
        }).catch(err => {
          logger.info('ChannelList: Fetching channels failed', err);
          channelListDispatcher({
            type: ChannelList_context.FETCH_CHANNELS_FAILURE,
            payload: err
          });
        });
      }
    }
  }, sdkError && !loading && (renderPlaceHolderError && typeof renderPlaceHolderError === 'function' ? renderPlaceHolderError === null || renderPlaceHolderError === void 0 ? void 0 : renderPlaceHolderError() : /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
    type: ui_PlaceHolder.PlaceHolderTypes.WRONG
  })), /*#__PURE__*/React__default["default"].createElement("div", null, allChannels && allChannels.map((channel, idx) => {
    // todo: Refactor and move this inside channel - preview
    const onLeaveChannel = (c, cb) => {
      logger.info('ChannelList: Leaving channel', c);
      c.leave().then(res => {
        logger.info('ChannelList: Leaving channel success', res);
        if (cb && typeof cb === 'function') {
          cb(res, null);
        }
        channelListDispatcher({
          type: ChannelList_context.LEAVE_CHANNEL_SUCCESS,
          payload: channel === null || channel === void 0 ? void 0 : channel.url
        });
      }).catch(err => {
        logger.error('ChannelList: Leaving channel failed', err);
        if (cb && typeof cb === 'function') {
          cb(null, err);
        }
      });
    };
    const onClick = () => {
      if (!isOnline) {
        return;
      }
      logger.info('ChannelList: Clicked on channel:', channel);
      channelListDispatcher({
        type: ChannelList_context.SET_CURRENT_CHANNEL,
        payload: channel
      });
    };
    return renderChannelPreview ?
    /*#__PURE__*/
    // eslint-disable-next-line
    React__default["default"].createElement("div", {
      key: channel === null || channel === void 0 ? void 0 : channel.url,
      onClick: onClick
    }, renderChannelPreview({
      channel,
      onLeaveChannel
    })) : /*#__PURE__*/React__default["default"].createElement(ChannelList_components_ChannelPreview, {
      key: channel === null || channel === void 0 ? void 0 : channel.url,
      tabIndex: idx,
      onClick: onClick,
      channel: channel,
      onLeaveChannel: () => onLeaveChannel(channel, null),
      isActive: (channel === null || channel === void 0 ? void 0 : channel.url) === (currentChannel === null || currentChannel === void 0 ? void 0 : currentChannel.url),
      isTyping: typingChannels === null || typingChannels === void 0 ? void 0 : typingChannels.some(_ref => {
        let {
          url
        } = _ref;
        return url === (channel === null || channel === void 0 ? void 0 : channel.url);
      }),
      renderChannelAction: () => /*#__PURE__*/React__default["default"].createElement(ChannelList_components_ChannelPreviewAction, {
        channel: channel,
        disabled: !isOnline,
        onLeaveChannel: () => onLeaveChannel(channel, null)
      })
    });
  })), !initialized && loading && (renderPlaceHolderLoading && typeof renderPlaceHolderLoading === 'function' ? renderPlaceHolderLoading === null || renderPlaceHolderLoading === void 0 ? void 0 : renderPlaceHolderLoading() : /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
    type: ui_PlaceHolder.PlaceHolderTypes.LOADING
  })), initialized && (allChannels === null || allChannels === void 0 ? void 0 : allChannels.length) === 0 && (renderPlaceHolderEmptyList && typeof renderPlaceHolderEmptyList === 'function' ? renderPlaceHolderEmptyList === null || renderPlaceHolderEmptyList === void 0 ? void 0 : renderPlaceHolderEmptyList() : /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
    type: ui_PlaceHolder.PlaceHolderTypes.NO_CHANNELS
  }))));
};

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