'use strict';

var _rollupPluginBabelHelpers = require('../../_rollupPluginBabelHelpers-acf412a3.js');
var React = require('react');
var LocalizationContext = require('../../LocalizationContext-8cc9717d.js');
var CreateChannel_context = require('../../CreateChannelProvider-36e598db.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var ui_Modal = require('../../ui/Modal.js');
var ui_Label = require('../../index-35633fb6.js');
var ui_Button = require('../../ui/Button.js');
var ui_UserListItem = require('../../ui/UserListItem.js');
require('../../stringSet-ce782136.js');
require('../../index-d749c4c2.js');
require('../../sendbirdSelectors.js');
require('../../topics-e24ef339.js');
require('../../utils-5aa0708e.js');
require('../../withSendbird.js');
require('react-dom');
require('../../index-8029e07a.js');
require('../../ui/Icon.js');
require('prop-types');
require('../../ui/IconButton.js');
require('../../MediaQueryContext-fad211ad.js');
require('../../UserProfileContext-d993c96b.js');
require('../../ui/Avatar.js');
require('../../ui/ImageRenderer.js');
require('../../uuid-1eceb0c8.js');
require('../../ui/MutedAvatarOverlay.js');
require('../../ui/Checkbox.js');
require('../../ui/UserProfile.js');
require('../../ui/ContextMenu.js');
require('../../ui/SortByRow.js');
require('../../index-a91b85d9.js');
require('../../utils/message/getOutgoingMessageState.js');

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

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

const filterUser = idsToFilter => currentId => idsToFilter === null || idsToFilter === void 0 ? void 0 : idsToFilter.includes(currentId);
const setChannelType = (params, type) => {
  if (type === 'broadcast') {
    // eslint-disable-next-line no-param-reassign
    params.isBroadcast = true;
  }
  if (type === 'supergroup') {
    // eslint-disable-next-line no-param-reassign
    params.isSuper = true;
  }
  return params;
};
const createDefaultUserListQuery = _ref => {
  let {
    sdk,
    userFilledApplicationUserListQuery
  } = _ref;
  if (sdk !== null && sdk !== void 0 && sdk.createApplicationUserListQuery) {
    const params = sdk === null || sdk === void 0 ? void 0 : sdk.createApplicationUserListQuery();
    if (userFilledApplicationUserListQuery) {
      Object.keys(userFilledApplicationUserListQuery).forEach(key => {
        params[key] = userFilledApplicationUserListQuery[key];
      });
    }
    return params;
  }
};

const appHeight = () => {
  try {
    const doc = document.documentElement;
    doc.style.setProperty('--sendbird-vh', window.innerHeight * 0.01 + 'px');
  } catch (_unused) {
    //
  }
};
const BUFFER = 50;
const InviteUsers = _ref => {
  var _globalStore$config, _globalStore$stores, _globalStore$stores$s;
  let {
    onCancel,
    userListQuery
  } = _ref;
  const {
    onBeforeCreateChannel,
    onCreateChannel,
    overrideInviteUser,
    createChannel,
    type
  } = CreateChannel_context.useCreateChannelContext();
  const globalStore = useSendbirdStateContext();
  const userId = globalStore === null || globalStore === void 0 ? void 0 : (_globalStore$config = globalStore.config) === null || _globalStore$config === void 0 ? void 0 : _globalStore$config.userId;
  const sdk = globalStore === null || globalStore === void 0 ? void 0 : (_globalStore$stores = globalStore.stores) === null || _globalStore$stores === void 0 ? void 0 : (_globalStore$stores$s = _globalStore$stores.sdkStore) === null || _globalStore$stores$s === void 0 ? void 0 : _globalStore$stores$s.sdk;
  const idsToFilter = [userId];
  const [users, setUsers] = React.useState([]);
  const [selectedUsers, setSelectedUsers] = React.useState({});
  const {
    stringSet
  } = React.useContext(LocalizationContext.LocalizationContext);
  const [usersDataSource, setUsersDataSource] = React.useState(null);
  const selectedCount = Object.keys(selectedUsers).length;
  const titleText = stringSet.MODAL__CREATE_CHANNEL__TITLE;
  const submitText = stringSet.BUTTON__CREATE;
  const userQueryCreator = userListQuery ? userListQuery() : createDefaultUserListQuery({
    sdk
  });
  React.useEffect(() => {
    const applicationUserListQuery = userQueryCreator;
    setUsersDataSource(applicationUserListQuery);
    // @ts-ignore
    if (!(applicationUserListQuery !== null && applicationUserListQuery !== void 0 && applicationUserListQuery.isLoading)) {
      applicationUserListQuery.next().then(users_ => {
        setUsers(users_);
      });
    }
  }, []);

  // https://stackoverflow.com/a/70302463
  // https://css-tricks.com/the-trick-to-viewport-units-on-mobile/#css-custom-properties-the-trick-to-correct-sizing
  // to fix navbar break in mobile
  React.useEffect(() => {
    appHeight();
    window.addEventListener('resize', appHeight);
    return () => {
      window.removeEventListener('resize', appHeight);
    };
  }, []);
  return /*#__PURE__*/React__default["default"].createElement(ui_Modal["default"], {
    isFullScreenOnMobile: true,
    titleText: titleText,
    submitText: submitText,
    type: ui_Button.ButtonTypes.PRIMARY
    // Disable the create button if no users are selected,
    // but if there's only the logged-in user in the user list,
    // then the create button should be enabled
    ,
    disabled: users.length > 1 && Object.keys(selectedUsers).length === 0,
    onCancel: onCancel,
    onSubmit: () => {
      const selectedUserList = Object.keys(selectedUsers).length > 0 ? Object.keys(selectedUsers) : [userId];
      if (typeof overrideInviteUser === 'function') {
        overrideInviteUser({
          users: selectedUserList,
          onClose: onCancel,
          channelType: type
        });
        return;
      }
      if (onBeforeCreateChannel) {
        const params = onBeforeCreateChannel(selectedUserList);
        setChannelType(params, type);
        createChannel(params).then(channel => {
          onCreateChannel(channel);
        });
      } else {
        const params = {};
        params.invitedUserIds = selectedUserList;
        params.isDistinct = false;
        if (userId) {
          params.operatorUserIds = [userId];
        }
        setChannelType(params, type);
        // do not have custom params
        createChannel(params).then(channel => {
          onCreateChannel(channel);
        });
      }
      onCancel();
    }
  }, /*#__PURE__*/React__default["default"].createElement("div", null, /*#__PURE__*/React__default["default"].createElement(ui_Label.Label, {
    color: selectedCount > 0 ? ui_Label.LabelColors.PRIMARY : ui_Label.LabelColors.ONBACKGROUND_3,
    type: ui_Label.LabelTypography.CAPTION_1
  }, `${selectedCount} ${stringSet.MODAL__INVITE_MEMBER__SELECTED}`), /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-create-channel--scroll",
    onScroll: e => {
      const eventTarget = e.target;
      const {
        hasNext
      } = usersDataSource;
      const fetchMore = eventTarget.clientHeight + eventTarget.scrollTop + BUFFER > eventTarget.scrollHeight;
      if (hasNext && fetchMore) {
        usersDataSource.next().then(usersBatch => {
          setUsers([...users, ...usersBatch]);
        });
      }
    }
  }, users.map(user => !filterUser(idsToFilter)(user.userId) && /*#__PURE__*/React__default["default"].createElement(ui_UserListItem, {
    key: user.userId,
    user: user,
    checkBox: true,
    checked: selectedUsers[user.userId],
    onChange: event => {
      const modifiedSelectedUsers = _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, selectedUsers), {}, {
        [event.target.id]: event.target.checked
      });
      if (!event.target.checked) {
        delete modifiedSelectedUsers[event.target.id];
      }
      setSelectedUsers(modifiedSelectedUsers);
    }
  })))));
};

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