'use strict';

var React = require('react');
var ui_Button = require('./ui/Button.js');
var ui_IconButton = require('./ui/IconButton.js');
var ui_Icon = require('./ui/Icon.js');
var ui_ContextMenu = require('./ui/ContextMenu.js');
var ChannelSettings_components_UserListItem = require('./ChannelSettings/components/UserListItem.js');
var _rollupPluginBabelHelpers = require('./_rollupPluginBabelHelpers-21ae158b.js');
var ui_Modal = require('./ui/Modal.js');
var ui_UserListItem = require('./ui/UserListItem.js');
var utils = require('./utils-6a748c02.js');
var ChannelSettings_context = require('./ChannelSettings/context.js');
var useSendbirdStateContext = require('./useSendbirdStateContext.js');
var LocalizationContext = require('./LocalizationContext-44d2f61b.js');
var uuid = require('./uuid-dee74248.js');

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

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

function MembersModal(_ref) {
  var _state$config;
  let {
    onCancel
  } = _ref;
  const [members, setMembers] = React.useState([]);
  const [memberQuery, setMemberQuery] = React.useState(null);
  const {
    channel
  } = ChannelSettings_context.useChannelSettingsContext();
  const state = useSendbirdStateContext();
  const currentUser = state === null || state === void 0 ? void 0 : (_state$config = state.config) === null || _state$config === void 0 ? void 0 : _state$config.userId;
  const {
    stringSet
  } = React.useContext(LocalizationContext.LocalizationContext);
  React.useEffect(() => {
    const memberListQuery = channel === null || channel === void 0 ? void 0 : channel.createMemberListQuery({
      limit: 20
    });
    memberListQuery.next().then(members => {
      setMembers(members);
    });
    setMemberQuery(memberListQuery);
  }, []);
  return /*#__PURE__*/React__default["default"].createElement("div", null, /*#__PURE__*/React__default["default"].createElement(ui_Modal["default"], {
    isFullScreenOnMobile: true,
    hideFooter: true,
    onCancel: () => onCancel(),
    onSubmit: utils.noop,
    titleText: stringSet.CHANNEL_SETTING__MEMBERS__SEE_ALL_MEMBERS
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-more-members__popup-scroll",
    onScroll: e => {
      const {
        hasNext
      } = memberQuery;
      const target = e.target;
      const fetchMore = target.clientHeight + target.scrollTop === target.scrollHeight;
      if (hasNext && fetchMore) {
        memberQuery.next().then(o => {
          setMembers([...members, ...o]);
        });
      }
    }
  }, members.map(member => /*#__PURE__*/React__default["default"].createElement(ui_UserListItem, {
    user: member,
    key: member.userId,
    currentUser: currentUser,
    action: _ref2 => {
      let {
        parentRef,
        actionRef
      } = _ref2;
      return /*#__PURE__*/React__default["default"].createElement(React__default["default"].Fragment, null, (channel === null || channel === void 0 ? void 0 : channel.myRole) === 'operator' && /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu["default"], {
        menuTrigger: toggleDropdown => /*#__PURE__*/React__default["default"].createElement(ui_IconButton, {
          className: "sendbird-user-message__more__menu",
          width: "32px",
          height: "32px",
          onClick: () => {
            toggleDropdown();
          }
        }, /*#__PURE__*/React__default["default"].createElement(ui_Icon["default"], {
          width: "24px",
          height: "24px",
          type: ui_Icon.IconTypes.MORE,
          fillColor: ui_Icon.IconColors.CONTENT_INVERSE
        })),
        menuItems: closeDropdown => /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu.MenuItems, {
          parentContainRef: parentRef,
          parentRef: actionRef // for catching location(x, y) of MenuItems
          ,
          closeDropdown: closeDropdown,
          openLeft: true
        }, /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu.MenuItem, {
          disable: currentUser === member.userId,
          onClick: () => {
            if (member.role !== 'operator') {
              channel === null || channel === void 0 ? void 0 : channel.addOperators([member.userId]).then(() => {
                setMembers(members.map(m => {
                  if (m.userId === member.userId) {
                    return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, member), {}, {
                      role: 'operator'
                    });
                  }
                  return m;
                }));
                closeDropdown();
              });
            } else {
              channel === null || channel === void 0 ? void 0 : channel.removeOperators([member.userId]).then(() => {
                setMembers(members.map(m => {
                  if (m.userId === member.userId) {
                    return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, member), {}, {
                      role: ''
                    });
                  }
                  return m;
                }));
                closeDropdown();
              });
            }
          },
          dataSbId: `channel_setting_member_context_menu_${member.role !== 'operator' ? 'register_as_operator' : 'unregister_operator'}`
        }, member.role !== 'operator' ? stringSet.CHANNEL_SETTING__MODERATION__REGISTER_AS_OPERATOR : stringSet.CHANNEL_SETTING__MODERATION__UNREGISTER_OPERATOR),
        // No muted members in broadcast channel
        !(channel !== null && channel !== void 0 && channel.isBroadcast) && /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu.MenuItem, {
          onClick: () => {
            if (member.isMuted) {
              channel === null || channel === void 0 ? void 0 : channel.unmuteUser(member).then(() => {
                setMembers(members.map(m => {
                  if (m.userId === member.userId) {
                    return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, member), {}, {
                      isMuted: false
                    });
                  }
                  return m;
                }));
                closeDropdown();
              });
            } else {
              channel === null || channel === void 0 ? void 0 : channel.muteUser(member).then(() => {
                setMembers(members.map(m => {
                  if (m.userId === member.userId) {
                    return _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, member), {}, {
                      isMuted: true
                    });
                  }
                  return m;
                }));
                closeDropdown();
              });
            }
          },
          dataSbId: `channel_setting_member_context_menu_${member.isMuted ? 'unmute' : 'mute'}`
        }, member.isMuted ? stringSet.CHANNEL_SETTING__MODERATION__UNMUTE : stringSet.CHANNEL_SETTING__MODERATION__MUTE), /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu.MenuItem, {
          onClick: () => {
            channel === null || channel === void 0 ? void 0 : channel.banUser(member, -1, '').then(() => {
              setMembers(members.filter(_ref3 => {
                let {
                  userId
                } = _ref3;
                return userId !== member.userId;
              }));
            });
          },
          dataSbId: "channel_setting_member_context_menu_ban"
        }, stringSet.CHANNEL_SETTING__MODERATION__BAN))
      }));
    }
  })))));
}

const isAboutSame = (a, b, px) => Math.abs(a - b) <= px;
function InviteUsers(_ref) {
  var _state$stores, _state$stores$sdkStor, _state$config;
  let {
    onCancel,
    onSubmit
  } = _ref;
  const [members, setMembers] = React.useState([]);
  const [selectedMembers, setSelectedMembers] = React.useState({});
  const [userQuery, setUserQuery] = React.useState(null);
  const state = useSendbirdStateContext();
  const sdk = state === null || state === void 0 ? void 0 : (_state$stores = state.stores) === null || _state$stores === void 0 ? void 0 : (_state$stores$sdkStor = _state$stores.sdkStore) === null || _state$stores$sdkStor === void 0 ? void 0 : _state$stores$sdkStor.sdk;
  const globalUserListQuery = state === null || state === void 0 ? void 0 : (_state$config = state.config) === null || _state$config === void 0 ? void 0 : _state$config.userListQuery;
  const {
    channel,
    overrideInviteUser,
    queries
  } = ChannelSettings_context.useChannelSettingsContext();
  const userFilledQuery = _rollupPluginBabelHelpers._objectSpread2({}, queries === null || queries === void 0 ? void 0 : queries.applicationUserListQuery);
  const {
    stringSet
  } = LocalizationContext.useLocalization();
  React.useEffect(() => {
    const userListQuery = globalUserListQuery ? globalUserListQuery() : sdk === null || sdk === void 0 ? void 0 : sdk.createApplicationUserListQuery(userFilledQuery);
    if (userListQuery !== null && userListQuery !== void 0 && userListQuery.next) {
      userListQuery.next().then(members => {
        setMembers(members);
      });
      setUserQuery(userListQuery);
    }
  }, [sdk]);
  return /*#__PURE__*/React__default["default"].createElement("div", null, /*#__PURE__*/React__default["default"].createElement(ui_Modal["default"], {
    isFullScreenOnMobile: true,
    disabled: Object.keys(selectedMembers).length === 0,
    submitText: stringSet.BUTTON__INVITE,
    type: ui_Button.ButtonTypes.PRIMARY,
    onCancel: () => onCancel(),
    onSubmit: () => {
      const members = Object.keys(selectedMembers).filter(m => selectedMembers[m]);
      if (typeof overrideInviteUser === 'function') {
        overrideInviteUser({
          users: members,
          onClose: onCancel,
          channel
        });
        return;
      }
      channel === null || channel === void 0 ? void 0 : channel.inviteWithUserIds(members).then(() => {
        onSubmit(members);
      });
    },
    titleText: stringSet.CHANNEL_SETTING__MEMBERS__SELECT_TITLE
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-more-members__popup-scroll",
    onScroll: e => {
      const {
        hasNext
      } = userQuery;
      const target = e.target;
      const fetchMore = isAboutSame(target.clientHeight + target.scrollTop, target.scrollHeight, 20);
      if (hasNext && fetchMore) {
        userQuery.next().then(users => {
          setMembers([...members, ...users]);
        });
      }
    }
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-more-members__popup-scroll__inner"
  }, members.map(member => {
    var _channel$members;
    const isJoinedMember = channel === null || channel === void 0 ? void 0 : (_channel$members = channel.members) === null || _channel$members === void 0 ? void 0 : _channel$members.some(_ref2 => {
      let {
        userId
      } = _ref2;
      return userId === (member === null || member === void 0 ? void 0 : member.userId);
    });
    return /*#__PURE__*/React__default["default"].createElement(ui_UserListItem, {
      checkBox: true,
      checked: isJoinedMember || selectedMembers[member.userId],
      disabled: isJoinedMember,
      onChange: event => {
        const modifiedSelectedMembers = _rollupPluginBabelHelpers._objectSpread2(_rollupPluginBabelHelpers._objectSpread2({}, selectedMembers), {}, {
          [event.target.id]: event.target.checked
        });
        if (!event.target.checked) {
          delete modifiedSelectedMembers[event.target.id];
        }
        setSelectedMembers(modifiedSelectedMembers);
      },
      user: member,
      key: member.userId
    });
  })))));
}

const MemberList = () => {
  var _state$stores, _state$stores$sdkStor, _state$config;
  const [members, setMembers] = React.useState([]);
  const [hasNext, setHasNext] = React.useState(false);
  const [showAllMembers, setShowAllMembers] = React.useState(false);
  const [showInviteUsers, setShowInviteUsers] = React.useState(false);
  const state = useSendbirdStateContext();
  const {
    channel,
    setChannelUpdateId
  } = ChannelSettings_context.useChannelSettingsContext();
  const {
    stringSet
  } = React.useContext(LocalizationContext.LocalizationContext);
  const sdk = state === null || state === void 0 ? void 0 : (_state$stores = state.stores) === null || _state$stores === void 0 ? void 0 : (_state$stores$sdkStor = _state$stores.sdkStore) === null || _state$stores$sdkStor === void 0 ? void 0 : _state$stores$sdkStor.sdk;
  const userId = state === null || state === void 0 ? void 0 : (_state$config = state.config) === null || _state$config === void 0 ? void 0 : _state$config.userId;
  React.useEffect(() => {
    if (!channel) {
      setMembers([]);
      return;
    }
    const memberUserListQuery = channel === null || channel === void 0 ? void 0 : channel.createMemberListQuery({
      limit: 10
    });
    memberUserListQuery.next().then(members => {
      setMembers(members);
      setHasNext(memberUserListQuery.hasNext);
    });
  }, [channel]);
  const refreshList = React.useCallback(() => {
    if (!channel) {
      setMembers([]);
      return;
    }
    const memberUserListQuery = channel === null || channel === void 0 ? void 0 : channel.createMemberListQuery({
      limit: 10
    });
    memberUserListQuery.next().then(members => {
      setMembers(members);
      setHasNext(memberUserListQuery.hasNext);
      setChannelUpdateId(uuid.uuidv4());
    });
  }, [channel]);
  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-channel-settings-member-list sendbird-accordion"
  }, members.map(member => /*#__PURE__*/React__default["default"].createElement(ChannelSettings_components_UserListItem, {
    key: member.userId,
    user: member,
    currentUser: sdk.currentUser.userId,
    action: (channel === null || channel === void 0 ? void 0 : channel.myRole) === 'operator' && userId !== member.userId ? _ref => {
      let {
        actionRef,
        parentRef
      } = _ref;
      return /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu["default"], {
        menuTrigger: toggleDropdown => /*#__PURE__*/React__default["default"].createElement(ui_IconButton, {
          className: "sendbird-user-message__more__menu",
          width: "32px",
          height: "32px",
          onClick: toggleDropdown
        }, /*#__PURE__*/React__default["default"].createElement(ui_Icon["default"], {
          width: "24px",
          height: "24px",
          type: ui_Icon.IconTypes.MORE,
          fillColor: ui_Icon.IconColors.CONTENT_INVERSE
        })),
        menuItems: closeDropdown => /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu.MenuItems, {
          parentContainRef: parentRef,
          parentRef: actionRef // for catching location(x, y) of MenuItems
          ,
          closeDropdown: closeDropdown,
          openLeft: true
        }, /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu.MenuItem, {
          onClick: () => {
            if (member.role !== 'operator') {
              channel === null || channel === void 0 ? void 0 : channel.addOperators([member.userId]).then(() => {
                refreshList();
                closeDropdown();
              });
            } else {
              channel === null || channel === void 0 ? void 0 : channel.removeOperators([member.userId]).then(() => {
                refreshList();
                closeDropdown();
              });
            }
          },
          dataSbId: `channel_setting_member_context_menu_${member.role !== 'operator' ? 'register_as_operator' : 'unregister_operator'}`
        }, member.role !== 'operator' ? stringSet.CHANNEL_SETTING__MODERATION__REGISTER_AS_OPERATOR : stringSet.CHANNEL_SETTING__MODERATION__UNREGISTER_OPERATOR),
        // No muted members in broadcast channel
        !(channel !== null && channel !== void 0 && channel.isBroadcast) && /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu.MenuItem, {
          onClick: () => {
            if (member.isMuted) {
              channel === null || channel === void 0 ? void 0 : channel.unmuteUser(member).then(() => {
                refreshList();
                closeDropdown();
              });
            } else {
              channel === null || channel === void 0 ? void 0 : channel.muteUser(member).then(() => {
                refreshList();
                closeDropdown();
              });
            }
          },
          dataSbId: `channel_setting_member_context_menu_${member.isMuted ? 'unmute' : 'mute'}`
        }, member.isMuted ? stringSet.CHANNEL_SETTING__MODERATION__UNMUTE : stringSet.CHANNEL_SETTING__MODERATION__MUTE), /*#__PURE__*/React__default["default"].createElement(ui_ContextMenu.MenuItem, {
          onClick: () => {
            channel === null || channel === void 0 ? void 0 : channel.banUser(member, -1, '').then(() => {
              refreshList();
              closeDropdown();
            });
          },
          dataSbId: "channel_setting_member_context_menu_ban"
        }, stringSet.CHANNEL_SETTING__MODERATION__BAN))
      });
    } : null
  })), /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-channel-settings-accordion__footer"
  }, hasNext && /*#__PURE__*/React__default["default"].createElement(ui_Button["default"], {
    type: ui_Button.ButtonTypes.SECONDARY,
    size: ui_Button.ButtonSizes.SMALL,
    onClick: () => setShowAllMembers(true)
  }, stringSet.CHANNEL_SETTING__MEMBERS__SEE_ALL_MEMBERS), /*#__PURE__*/React__default["default"].createElement(ui_Button["default"], {
    type: ui_Button.ButtonTypes.SECONDARY,
    size: ui_Button.ButtonSizes.SMALL,
    onClick: () => setShowInviteUsers(true)
  }, stringSet.CHANNEL_SETTING__MEMBERS__INVITE_MEMBER)), showAllMembers && /*#__PURE__*/React__default["default"].createElement(MembersModal, {
    onCancel: () => {
      setShowAllMembers(false);
      refreshList();
    }
  }), showInviteUsers && /*#__PURE__*/React__default["default"].createElement(InviteUsers, {
    onSubmit: () => {
      setShowInviteUsers(false);
      refreshList();
    },
    onCancel: () => setShowInviteUsers(false)
  }));
};

exports.MemberList = MemberList;
//# sourceMappingURL=MemberList-324a4047.js.map
