"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const Vue = require("vue");
const basic = require("../../../stores/basic.js");
const room = require("../../../stores/room.js");
const chat = require("../../../stores/chat.js");
const pinia = require("pinia");
const index = require("../../../locales/index.js");
const useRoomEngine = require("../../../hooks/useRoomEngine.js");
const TUIRoomEngine = require("@tencentcloud/tuiroom-engine-js");
const index$1 = require("../../../utils/common/logger/index.js");
const Message = require("../../common/base/Message/Message.js");
require("../../../services/main.js");
const roomService = require("../../../services/roomService.js");
require("mitt");
require("../../../services/manager/roomActionManager.js");
require("@tencentcloud/tui-core");
function useEndControl() {
  const { t } = index.useI18n();
  let DialogType;
  ((DialogType2) => {
    DialogType2[DialogType2["BasicDialog"] = 0] = "BasicDialog";
    DialogType2[DialogType2["TransferDialog"] = 1] = "TransferDialog";
  })(DialogType || (DialogType = {}));
  const currentDialogType = Vue.ref(
    0
    /* BasicDialog */
  );
  const logPrefix = "[EndControl]";
  const roomEngine = useRoomEngine.default();
  const visible = Vue.ref(false);
  const basicStore = basic.useBasicStore();
  const chatStore = chat.useChatStore();
  index$1.default.log(`${logPrefix} basicStore:`, basicStore);
  const roomStore = room.useRoomStore();
  const { localUser, remoteEnteredUserList, applyToAnchorList } = pinia.storeToRefs(roomStore);
  const title = Vue.computed(
    () => currentDialogType.value === 0 ? t("Leave room?") : t("Select a new host")
  );
  const isShowLeaveRoomDialog = Vue.computed(
    () => roomStore.isMaster && remoteEnteredUserList.value.length > 0 || !roomStore.isMaster
  );
  const { isSidebarOpen, sidebarName } = pinia.storeToRefs(basicStore);
  const showSideBar = Vue.computed(
    () => isSidebarOpen.value && sidebarName.value === "transfer-leave"
  );
  const selectedUser = Vue.ref("");
  const showTransfer = Vue.ref(false);
  const searchName = Vue.ref("");
  const filteredList = Vue.computed(
    () => remoteEnteredUserList.value.filter(
      (searchUser) => {
        var _a, _b;
        return ((_a = searchUser.nameCard) == null ? void 0 : _a.includes(searchName.value)) || searchUser.userId.includes(searchName.value) || ((_b = searchUser.userName) == null ? void 0 : _b.includes(searchName.value));
      }
    )
  );
  const hasNoData = Vue.computed(() => filteredList.value.length === 0);
  const isMasterWithOneRemoteUser = Vue.computed(
    () => remoteEnteredUserList.value.length === 1
  );
  const isMasterWithRemoteUser = Vue.computed(
    () => remoteEnteredUserList.value.length > 0
  );
  const isMasterWithoutRemoteUser = Vue.computed(
    () => roomStore.isMaster && remoteEnteredUserList.value.length === 0
  );
  const showEndButtonContent = Vue.computed(
    () => roomStore.isMaster ? t("EndPC") : t("Leave")
  );
  const showEndDialogContent = Vue.computed(
    () => roomStore.isMaster ? isMasterWithoutRemoteUser.value ? t(
      'You are currently the host of the room, please choose the corresponding operation. If you choose "End Room", the current room will be disbanded and all members will be removed.'
    ) : t(
      'You are currently the host of the room, please choose the corresponding operation. If you choose "End Room", the current room will be disbanded and all members will be removed. If you choose "Leave Room", the current room will not be disbanded, and your hosting privileges will be transferred to other members.'
    ) : t("Are you sure you want to leave this room?")
  );
  function toggleMangeMemberSidebar() {
    if (basicStore.setSidebarOpenStatus && sidebarName.value === "transfer-leave") {
      basicStore.setSidebarOpenStatus(false);
      basicStore.setSidebarName("");
      return;
    }
    basicStore.setSidebarOpenStatus(true);
    basicStore.setSidebarName("transfer-leave");
  }
  function handleShowMemberControl(userId) {
    selectedUser.value = userId;
  }
  function resetState() {
    visible.value = false;
    currentDialogType.value = 0;
  }
  function stopMeeting() {
    if (!visible.value) {
      visible.value = true;
    }
  }
  function cancel() {
    resetState();
  }
  function closeMediaBeforeLeave() {
    var _a, _b;
    if (localUser.value.hasAudioStream) {
      (_a = roomEngine.instance) == null ? void 0 : _a.closeLocalMicrophone();
    }
    if (localUser.value.hasVideoStream) {
      (_b = roomEngine.instance) == null ? void 0 : _b.closeLocalCamera();
    }
  }
  async function handleUpdateSeatApplicationList() {
    var _a;
    if (!roomStore.isSpeakAfterTakingSeatMode) {
      return;
    }
    if (applyToAnchorList.value.length > 0) {
      applyToAnchorList.value.forEach((user) => {
        user.applyToAnchorRequestId && roomStore.removeApplyToAnchorUser(user.applyToAnchorRequestId);
      });
    }
    const applicationList = await ((_a = roomEngine.instance) == null ? void 0 : _a.getSeatApplicationList());
    if (applicationList && applicationList.length > 0) {
      for (const applicationInfo of applicationList) {
        const { userId, requestId, timestamp } = applicationInfo;
        roomStore.addApplyToAnchorUser({ userId, requestId, timestamp });
      }
    }
  }
  const onUserRoleChanged = async (eventInfo) => {
    var _a, _b;
    const { userId, userRole } = eventInfo;
    const isLocal = roomStore.localUser.userId === userId;
    const oldUserRole = roomStore.getUserRole(userId);
    roomStore.updateUserInfo({ userId, userRole });
    switch (userRole) {
      case TUIRoomEngine.TUIRole.kGeneralUser:
        if (isLocal) {
          if ((roomStore == null ? void 0 : roomStore.isMicrophoneDisableForAllUser) && !roomStore.localStream.hasAudioStream) {
            roomStore.setCanControlSelfAudio(false);
          }
          if ((roomStore == null ? void 0 : roomStore.isCameraDisableForAllUser) && !roomStore.localStream.hasVideoStream) {
            roomStore.setCanControlSelfVideo(false);
          }
          if (oldUserRole === TUIRoomEngine.TUIRole.kAdministrator) {
            Message.default({
              type: "warning",
              message: t("Your administrator status has been revoked")
            });
          }
          if (roomStore.localStream.hasAudioStream) {
            roomStore.setCanControlSelfAudio(true);
          }
          if (roomStore.localStream.hasVideoStream) {
            roomStore.setCanControlSelfVideo(true);
          }
        }
        break;
      case TUIRoomEngine.TUIRole.kAdministrator:
        if (isLocal) {
          Message.default({
            type: "success",
            message: t("You have become a administrator")
          });
          roomStore.setCanControlSelfAudio(true);
          roomStore.setCanControlSelfVideo(true);
          if (roomStore.isSpeakAfterTakingSeatMode) {
            handleUpdateSeatApplicationList();
          }
        }
        break;
      case TUIRoomEngine.TUIRole.kRoomOwner: {
        roomStore.setMasterUserId(userId);
        if (isLocal) {
          Message.default({
            type: "success",
            message: `${t("You are now a room owner")}`
          });
          if (roomStore.isSpeakAfterTakingSeatMode) {
            if (!roomStore.isAnchor) {
              await ((_a = roomEngine.instance) == null ? void 0 : _a.takeSeat({
                seatIndex: -1,
                timeout: 0
              }));
            }
            handleUpdateSeatApplicationList();
          }
          if (chatStore.isMessageDisabled) {
            (_b = roomEngine.instance) == null ? void 0 : _b.disableSendingMessageByAdmin({
              userId,
              isDisable: false
            });
          }
        }
        break;
      }
    }
  };
  TUIRoomEngine.once("ready", () => {
    var _a;
    (_a = roomEngine.instance) == null ? void 0 : _a.on(TUIRoomEngine.TUIRoomEvents.onUserRoleChanged, onUserRoleChanged);
  });
  const handleMount = () => {
    const { userRole } = roomService.roomService.roomStore.localUser;
    if (userRole === TUIRoomEngine.TUIRole.kRoomOwner || userRole === TUIRoomEngine.TUIRole.kAdministrator) {
      handleUpdateSeatApplicationList();
    }
  };
  roomService.roomService.lifeCycleManager.on("mount", handleMount);
  Vue.onUnmounted(() => {
    var _a;
    (_a = roomEngine.instance) == null ? void 0 : _a.off(
      TUIRoomEngine.TUIRoomEvents.onUserRoleChanged,
      onUserRoleChanged
    );
    roomService.roomService.lifeCycleManager.off("mount", handleMount);
  });
  return {
    t,
    basicStore,
    isShowLeaveRoomDialog,
    roomStore,
    roomEngine,
    localUser,
    stopMeeting,
    cancel,
    selectedUser,
    showEndButtonContent,
    DialogType,
    showEndDialogContent,
    logPrefix,
    title,
    currentDialogType,
    visible,
    closeMediaBeforeLeave,
    resetState,
    searchName,
    hasNoData,
    handleShowMemberControl,
    filteredList,
    toggleMangeMemberSidebar,
    showTransfer,
    sidebarName,
    showSideBar,
    isMasterWithOneRemoteUser,
    isMasterWithRemoteUser,
    remoteEnteredUserList
  };
}
exports.default = useEndControl;
