import { ref, computed, onUnmounted } from "vue";
import { useBasicStore } from "../../../stores/basic.mjs";
import { useRoomStore } from "../../../stores/room.mjs";
import { useChatStore } from "../../../stores/chat.mjs";
import { storeToRefs } from "pinia";
import { useI18n } from "../../../locales/index.mjs";
import useGetRoomEngine from "../../../hooks/useRoomEngine.mjs";
import TUIRoomEngine__default, { TUIRoomEvents, TUIRole } from "@tencentcloud/tuiroom-engine-js";
import logger from "../../../utils/common/logger/index.mjs";
import renderMsg from "../../common/base/Message/Message.mjs";
import "../../../services/main.mjs";
import { roomService } from "../../../services/roomService.mjs";
import "mitt";
import "../../../services/manager/roomActionManager.mjs";
import "@tencentcloud/tui-core";
function useEndControl() {
  const { t } = useI18n();
  let DialogType;
  ((DialogType2) => {
    DialogType2[DialogType2["BasicDialog"] = 0] = "BasicDialog";
    DialogType2[DialogType2["TransferDialog"] = 1] = "TransferDialog";
  })(DialogType || (DialogType = {}));
  const currentDialogType = ref(
    0
    /* BasicDialog */
  );
  const logPrefix = "[EndControl]";
  const roomEngine = useGetRoomEngine();
  const visible = ref(false);
  const basicStore = useBasicStore();
  const chatStore = useChatStore();
  logger.log(`${logPrefix} basicStore:`, basicStore);
  const roomStore = useRoomStore();
  const { localUser, remoteEnteredUserList, applyToAnchorList } = storeToRefs(roomStore);
  const title = computed(
    () => currentDialogType.value === 0 ? t("Leave room?") : t("Select a new host")
  );
  const isShowLeaveRoomDialog = computed(
    () => roomStore.isMaster && remoteEnteredUserList.value.length > 0 || !roomStore.isMaster
  );
  const { isSidebarOpen, sidebarName } = storeToRefs(basicStore);
  const showSideBar = computed(
    () => isSidebarOpen.value && sidebarName.value === "transfer-leave"
  );
  const selectedUser = ref("");
  const showTransfer = ref(false);
  const searchName = ref("");
  const filteredList = 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 = computed(() => filteredList.value.length === 0);
  const isMasterWithOneRemoteUser = computed(
    () => remoteEnteredUserList.value.length === 1
  );
  const isMasterWithRemoteUser = computed(
    () => remoteEnteredUserList.value.length > 0
  );
  const isMasterWithoutRemoteUser = computed(
    () => roomStore.isMaster && remoteEnteredUserList.value.length === 0
  );
  const showEndButtonContent = computed(
    () => roomStore.isMaster ? t("EndPC") : t("Leave")
  );
  const showEndDialogContent = 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 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 === TUIRole.kAdministrator) {
            renderMsg({
              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 TUIRole.kAdministrator:
        if (isLocal) {
          renderMsg({
            type: "success",
            message: t("You have become a administrator")
          });
          roomStore.setCanControlSelfAudio(true);
          roomStore.setCanControlSelfVideo(true);
          if (roomStore.isSpeakAfterTakingSeatMode) {
            handleUpdateSeatApplicationList();
          }
        }
        break;
      case TUIRole.kRoomOwner: {
        roomStore.setMasterUserId(userId);
        if (isLocal) {
          renderMsg({
            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__default.once("ready", () => {
    var _a;
    (_a = roomEngine.instance) == null ? void 0 : _a.on(TUIRoomEvents.onUserRoleChanged, onUserRoleChanged);
  });
  const handleMount = () => {
    const { userRole } = roomService.roomStore.localUser;
    if (userRole === TUIRole.kRoomOwner || userRole === TUIRole.kAdministrator) {
      handleUpdateSeatApplicationList();
    }
  };
  roomService.lifeCycleManager.on("mount", handleMount);
  onUnmounted(() => {
    var _a;
    (_a = roomEngine.instance) == null ? void 0 : _a.off(
      TUIRoomEvents.onUserRoleChanged,
      onUserRoleChanged
    );
    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
  };
}
export {
  useEndControl as default
};
