var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import mitt from "mitt";
import useGetRoomEngine from "../hooks/useRoomEngine.mjs";
import { EventType } from "./types.mjs";
import TUIRoomEngine__default, { TUIRoomEvents, TUIKickedOutOfRoomReason, TUIRole, TRTCVideoMirrorType, TRTCVideoRotation, TRTCVideoFillMode } from "@tencentcloud/tuiroom-engine-js";
import { useBasicStore } from "../stores/basic.mjs";
import { useRoomStore } from "../stores/room.mjs";
import { useChatStore } from "../stores/chat.mjs";
import useDeviceManager from "../hooks/useDeviceManager.mjs";
import logger from "../utils/common/logger/index.mjs";
import { isMobile } from "../utils/environment.mjs";
import i18n from "../locales/index.mjs";
import { MESSAGE_DURATION } from "../constants/message.mjs";
import { ComponentManager } from "./manager/componentManager.mjs";
import { ConfigManager } from "./manager/configManager.mjs";
import { UserManager } from "./manager/userManager.mjs";
import { LifeCycleManager } from "./manager/lifeCycleManager.mjs";
import { MediaManager } from "./manager/MediaManager.mjs";
import { RoomActionManager } from "./manager/roomActionManager.mjs";
import { WaterMark } from "./function/waterMark.mjs";
import { VirtualBackground } from "./function/virtualBackground.mjs";
import { BasicBeauty } from "./function/basicBeauty.mjs";
import { ScheduleConferenceManager } from "./manager/scheduleConferenceManager.mjs";
import { ConferenceInvitationManager } from "./manager/conferenceInvitationManager.mjs";
import { ErrorHandler } from "./function/errorHandler.mjs";
import { ChatManager } from "./manager/chatManager.mjs";
import { TUILogin } from "@tencentcloud/tui-core";
const { t } = i18n.global;
const logPrefix = "[RoomService]";
const roomEngine = useGetRoomEngine();
const _RoomService = class _RoomService {
  constructor() {
    __publicField(this, "emitter", mitt());
    __publicField(this, "componentManager", new ComponentManager(this));
    __publicField(this, "configManager", new ConfigManager(this));
    __publicField(this, "userManager", new UserManager(this));
    __publicField(this, "mediaManager", new MediaManager(this));
    __publicField(this, "lifeCycleManager", new LifeCycleManager(this));
    __publicField(this, "roomActionManager", new RoomActionManager(this));
    __publicField(this, "waterMark", new WaterMark(this));
    __publicField(this, "virtualBackground", new VirtualBackground(this));
    __publicField(this, "basicBeauty", new BasicBeauty(this));
    __publicField(this, "scheduleConferenceManager", new ScheduleConferenceManager(this));
    __publicField(this, "conferenceInvitationManager", new ConferenceInvitationManager(this));
    __publicField(this, "errorHandler", new ErrorHandler(this));
    __publicField(this, "chatManager", new ChatManager(this));
    __publicField(this, "roomEngine", roomEngine);
    __publicField(this, "t", t);
    this.lifeCycleManager.start();
    this.initEventCtx();
    TUIRoomEngine__default.once("ready", () => {
      this.bindRoomEngineEvents();
      this.handleRoomEngineReady();
      this.emit(EventType.SERVICE_READY);
    });
  }
  get basicStore() {
    return useBasicStore();
  }
  get roomStore() {
    return useRoomStore();
  }
  get chatStore() {
    return useChatStore();
  }
  initEventCtx() {
    this.onError = this.onError.bind(this);
    this.onRoomDismissed = this.onRoomDismissed.bind(this);
    this.onUserVoiceVolumeChanged = this.onUserVoiceVolumeChanged.bind(this);
    this.onUserNetworkQualityChanged = this.onUserNetworkQualityChanged.bind(this);
    this.onKickedOutOfRoom = this.onKickedOutOfRoom.bind(this);
    this.onSendMessageForUserDisableChanged = this.onSendMessageForUserDisableChanged.bind(this);
    this.onUserSigExpired = this.onUserSigExpired.bind(this);
    this.onKickedOffLine = this.onKickedOffLine.bind(this);
    this.onAllUserCameraDisableChanged = this.onAllUserCameraDisableChanged.bind(this);
    this.onAllUserMicrophoneDisableChanged = this.onAllUserMicrophoneDisableChanged.bind(this);
    this.onScreenShareForAllUserDisableChanged = this.onScreenShareForAllUserDisableChanged.bind(this);
    this.onUserInfoChanged = this.onUserInfoChanged.bind(this);
  }
  static getInstance() {
    if (!_RoomService.instance) {
      _RoomService.instance = new _RoomService();
    }
    return _RoomService.instance;
  }
  static destroyInstance() {
    if (!_RoomService.instance) return;
    _RoomService.instance.lifeCycleManager.stop();
    _RoomService.instance.unBindRoomEngineEvents();
    _RoomService.instance.waterMark.dispose();
    _RoomService.instance.virtualBackground.dispose();
    _RoomService.instance.basicBeauty.dispose();
    _RoomService.instance.scheduleConferenceManager.dispose();
    _RoomService.instance.conferenceInvitationManager.dispose();
    _RoomService.instance.mediaManager.dispose();
    _RoomService.instance.chatManager.dispose();
    _RoomService.instance = void 0;
  }
  useExtension(extension) {
    extension._bind(this);
  }
  getRoomContainer() {
    return document.fullscreenElement || document.getElementById("roomContainer") || document.body;
  }
  initMediaDeviceList() {
    useDeviceManager({ listenForDeviceChange: true });
  }
  bindRoomEngineEvents() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
    (_a = roomEngine.instance) == null ? void 0 : _a.on(TUIRoomEvents.onError, this.onError);
    (_b = roomEngine.instance) == null ? void 0 : _b.on(
      TUIRoomEvents.onRoomDismissed,
      this.onRoomDismissed
    );
    (_c = roomEngine.instance) == null ? void 0 : _c.on(
      TUIRoomEvents.onUserVoiceVolumeChanged,
      this.onUserVoiceVolumeChanged
    );
    (_d = roomEngine.instance) == null ? void 0 : _d.on(
      TUIRoomEvents.onUserNetworkQualityChanged,
      this.onUserNetworkQualityChanged
    );
    (_e = roomEngine.instance) == null ? void 0 : _e.on(
      TUIRoomEvents.onKickedOutOfRoom,
      this.onKickedOutOfRoom
    );
    (_f = roomEngine.instance) == null ? void 0 : _f.on(
      TUIRoomEvents.onSendMessageForUserDisableChanged,
      this.onSendMessageForUserDisableChanged
    );
    (_g = roomEngine.instance) == null ? void 0 : _g.on(
      TUIRoomEvents.onUserSigExpired,
      this.onUserSigExpired
    );
    (_h = roomEngine.instance) == null ? void 0 : _h.on(
      TUIRoomEvents.onKickedOffLine,
      this.onKickedOffLine
    );
    (_i = roomEngine.instance) == null ? void 0 : _i.on(
      TUIRoomEvents.onAllUserCameraDisableChanged,
      this.onAllUserCameraDisableChanged
    );
    (_j = roomEngine.instance) == null ? void 0 : _j.on(
      TUIRoomEvents.onAllUserMicrophoneDisableChanged,
      this.onAllUserMicrophoneDisableChanged
    );
    (_k = roomEngine.instance) == null ? void 0 : _k.on(
      TUIRoomEvents.onScreenShareForAllUserDisableChanged,
      this.onScreenShareForAllUserDisableChanged
    );
    (_l = roomEngine.instance) == null ? void 0 : _l.on(
      TUIRoomEvents.onUserInfoChanged,
      this.onUserInfoChanged
    );
  }
  unBindRoomEngineEvents() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
    (_a = roomEngine.instance) == null ? void 0 : _a.off(TUIRoomEvents.onError, this.onError);
    (_b = roomEngine.instance) == null ? void 0 : _b.off(
      TUIRoomEvents.onRoomDismissed,
      this.onRoomDismissed
    );
    (_c = roomEngine.instance) == null ? void 0 : _c.off(
      TUIRoomEvents.onUserVoiceVolumeChanged,
      this.onUserVoiceVolumeChanged
    );
    (_d = roomEngine.instance) == null ? void 0 : _d.off(
      TUIRoomEvents.onUserNetworkQualityChanged,
      this.onUserNetworkQualityChanged
    );
    (_e = roomEngine.instance) == null ? void 0 : _e.off(
      TUIRoomEvents.onKickedOutOfRoom,
      this.onKickedOutOfRoom
    );
    (_f = roomEngine.instance) == null ? void 0 : _f.off(
      TUIRoomEvents.onSendMessageForUserDisableChanged,
      this.onSendMessageForUserDisableChanged
    );
    (_g = roomEngine.instance) == null ? void 0 : _g.off(
      TUIRoomEvents.onUserSigExpired,
      this.onUserSigExpired
    );
    (_h = roomEngine.instance) == null ? void 0 : _h.off(
      TUIRoomEvents.onKickedOffLine,
      this.onKickedOffLine
    );
    (_i = roomEngine.instance) == null ? void 0 : _i.off(
      TUIRoomEvents.onAllUserCameraDisableChanged,
      this.onAllUserCameraDisableChanged
    );
    (_j = roomEngine.instance) == null ? void 0 : _j.off(
      TUIRoomEvents.onAllUserMicrophoneDisableChanged,
      this.onAllUserMicrophoneDisableChanged
    );
    (_k = roomEngine.instance) == null ? void 0 : _k.off(
      TUIRoomEvents.onScreenShareForAllUserDisableChanged,
      this.onScreenShareForAllUserDisableChanged
    );
    (_l = roomEngine.instance) == null ? void 0 : _l.off(
      TUIRoomEvents.onUserInfoChanged,
      this.onUserInfoChanged
    );
  }
  onError(error) {
    logger.error("roomEngine.onError: ", error);
    this.errorHandler.handleError(error, "onError");
  }
  onRoomDismissed(eventInfo) {
    const { roomId } = eventInfo;
    logger.log(`${logPrefix}onRoomDismissed:`, roomId);
    this.emit(EventType.ROOM_NOTICE_MESSAGE_BOX, {
      title: t("Note"),
      message: t("The host closed the room."),
      confirmButtonText: t("Sure"),
      duration: 5e3,
      callback: async () => {
        this.emit(EventType.ROOM_DISMISS, {});
        this.resetStore();
      }
    });
  }
  onUserVoiceVolumeChanged(eventInfo) {
    const { userVolumeList } = eventInfo;
    this.roomStore.setAudioVolume(userVolumeList);
  }
  onUserNetworkQualityChanged(eventInfo) {
    this.basicStore.setLocalQuality(eventInfo.userNetworkList);
  }
  async onKickedOutOfRoom(eventInfo) {
    const { roomId, reason, message } = eventInfo;
    try {
      let notice = "";
      switch (reason) {
        case TUIKickedOutOfRoomReason.kKickedByAdmin:
          notice = t("kicked out of the room by the host");
          break;
        case TUIKickedOutOfRoomReason.kKickedByLoggedOnOtherDevice:
          notice = t("kicked out of the room by other device");
          break;
        case TUIKickedOutOfRoomReason.kKickedByServer:
          notice = t("kicked out of the room by serve");
          break;
      }
      this.emit(EventType.ROOM_NOTICE_MESSAGE_BOX, {
        title: t("Note"),
        message: notice,
        confirmButtonText: t("Sure"),
        callback: async () => {
          this.emit(EventType.KICKED_OUT, { roomId, reason, message });
          this.resetStore();
        }
      });
    } catch (error) {
      logger.error(`${logPrefix}onKickedOutOfRoom error:`, error);
    }
  }
  onSendMessageForUserDisableChanged(data) {
    const { userId, isDisable } = data;
    if (userId === this.roomStore.localUser.userId) {
      const tipMessage = isDisable ? t("You have been banned from text chat") : t("You are allowed to text chat");
      this.emit(EventType.ROOM_NOTICE_MESSAGE, {
        code: -1,
        type: "warning",
        message: tipMessage,
        duration: MESSAGE_DURATION.NORMAL
      });
      this.chatStore.setSendMessageDisableChanged(isDisable);
    }
    this.roomStore.setMuteUserChat(userId, isDisable);
  }
  onUserSigExpired() {
    this.emit(EventType.ROOM_NOTICE_MESSAGE_BOX, {
      title: t("Note"),
      message: t("userSig has expired"),
      confirmButtonText: t("Sure"),
      callback: () => {
        this.emit(EventType.USER_SIG_EXPIRED, {});
        this.resetStore();
      }
    });
  }
  onKickedOffLine(eventInfo) {
    const { message } = eventInfo;
    this.emit(EventType.ROOM_NOTICE_MESSAGE_BOX, {
      title: t("Note"),
      message: t(
        "The system has detected that your account has been kicked offline"
      ),
      confirmButtonText: t("Sure"),
      callback: async () => {
        this.emit(EventType.KICKED_OFFLINE, { message });
      }
    });
  }
  async onAllUserCameraDisableChanged(eventInfo) {
    const { isDisable } = eventInfo;
    if (isDisable !== this.roomStore.isCameraDisableForAllUser && this.roomStore.localUser.userRole === TUIRole.kGeneralUser) {
      this.roomStore.setCanControlSelfVideo(!isDisable);
    }
    this.handleVideoStateChange(isDisable);
    this.roomStore.setDisableCameraForAllUserByAdmin(isDisable);
  }
  async handleVideoStateChange(isDisableVideo) {
    var _a;
    const tipMessage = isDisableVideo ? t("All videos disabled") : t("All videos enabled");
    this.emit(EventType.ROOM_NOTICE_MESSAGE, {
      type: "success",
      message: tipMessage,
      duration: MESSAGE_DURATION.NORMAL
    });
    if (isDisableVideo && this.roomStore.localUser.userRole === TUIRole.kGeneralUser) {
      await ((_a = roomEngine.instance) == null ? void 0 : _a.closeLocalCamera());
    }
  }
  async onUserInfoChanged(eventInfo) {
    const { userId, nameCard } = eventInfo.userInfo;
    this.roomStore.updateUserInfo({ userId, nameCard });
  }
  async onAllUserMicrophoneDisableChanged(eventInfo) {
    const { isDisable } = eventInfo;
    if (isDisable !== this.roomStore.isMicrophoneDisableForAllUser && this.roomStore.localUser.userRole === TUIRole.kGeneralUser) {
      this.roomStore.setCanControlSelfAudio(!isDisable);
    }
    this.handleAudioStateChange(isDisable);
    this.roomStore.setDisableMicrophoneForAllUserByAdmin(isDisable);
  }
  async handleAudioStateChange(isDisableAudio) {
    var _a;
    const tipMessage = isDisableAudio ? t("All audios disabled") : t("All audios enabled");
    this.emit(EventType.ROOM_NOTICE_MESSAGE, {
      type: "success",
      message: tipMessage,
      duration: MESSAGE_DURATION.NORMAL
    });
    if (isDisableAudio && this.roomStore.localUser.userRole === TUIRole.kGeneralUser) {
      await ((_a = roomEngine.instance) == null ? void 0 : _a.muteLocalAudio());
    }
  }
  async onScreenShareForAllUserDisableChanged(eventInfo) {
    const { isDisable } = eventInfo;
    this.roomStore.setDisableScreenShareForAllUserByAdmin(isDisable);
  }
  resetStore() {
    this.basicStore.reset();
    this.chatStore.reset();
    this.roomStore.reset();
  }
  storeInit(option) {
    this.basicStore.setBasicInfo(option);
    this.userManager.setLocalUser(option);
  }
  async initRoomKit(option) {
    this.storeInit(option);
    const {
      sdkAppId,
      userId,
      userSig,
      userName = userId,
      avatarUrl = ""
    } = option;
    TUILogin.login({
      SDKAppID: sdkAppId,
      userID: userId,
      userSig,
      useUploadPlugin: true
    });
    const { chat } = TUILogin.getContext();
    await TUIRoomEngine__default.login({ sdkAppId, userId, userSig, tim: chat });
    await TUIRoomEngine__default.setSelfInfo({ userName, avatarUrl });
    this.emit(EventType.ROOM_LOGIN);
  }
  async start(roomId, params) {
    return this.roomActionManager.start(roomId, params);
  }
  async join(roomId, params) {
    return this.roomActionManager.join(roomId, params);
  }
  async createRoom(options) {
    await this.roomActionManager.createRoom(options);
  }
  async enterRoom(options) {
    await this.roomActionManager.enterRoom(options);
  }
  async leaveRoom() {
    await this.roomActionManager.leaveRoom();
  }
  async dismissRoom() {
    await this.roomActionManager.dismissRoom();
  }
  fetchRoomInfo(options) {
    return this.roomActionManager.fetchRoomInfo(options);
  }
  async handleRoomEngineReady() {
    var _a;
    const storageCurrentTheme = localStorage.getItem("tuiRoom-currentTheme");
    storageCurrentTheme && this.basicStore.setDefaultTheme(storageCurrentTheme);
    const trtcCloud = (_a = roomEngine.instance) == null ? void 0 : _a.getTRTCCloud();
    const mirrorType = isMobile ? TRTCVideoMirrorType.TRTCVideoMirrorType_Auto : this.basicStore.isLocalStreamMirror ? TRTCVideoMirrorType.TRTCVideoMirrorType_Enable : TRTCVideoMirrorType.TRTCVideoMirrorType_Disable;
    await (trtcCloud == null ? void 0 : trtcCloud.setLocalRenderParams({
      mirrorType,
      rotation: TRTCVideoRotation.TRTCVideoRotation0,
      fillMode: TRTCVideoFillMode.TRTCVideoFillMode_Fill
    }));
  }
  logOut() {
    this.emit(EventType.USER_LOGOUT);
    this.resetStore();
  }
  on(eventType, callback) {
    this.emitter.on(eventType, callback);
  }
  off(eventType, callback) {
    this.emitter.off(eventType, callback);
  }
  emit(eventType, data) {
    this.emitter.emit(eventType, data);
  }
  // Component Manager
  getComponentConfig(name) {
    return this.componentManager.getComponentConfig(name);
  }
  setComponentConfig(options) {
    return this.componentManager.setComponentConfig(options);
  }
  // Config Manager
  setTheme(theme) {
    return this.configManager.setTheme(theme);
  }
  setLanguage(language) {
    return this.configManager.setLanguage(language);
  }
  // User Manager
  setSelfInfo(options) {
    return this.userManager.setSelfInfo(options);
  }
  getDisplayName(options) {
    return this.userManager.getDisplayName(options);
  }
  getMediaManager() {
    return this.mediaManager;
  }
};
__publicField(_RoomService, "instance");
let RoomService = _RoomService;
const roomService = RoomService.getInstance();
export {
  RoomService,
  roomEngine,
  roomService
};
