"use strict";
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);
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const mitt = require("mitt");
const useRoomEngine = require("../hooks/useRoomEngine.js");
const types = require("./types.js");
const TUIRoomEngine = require("@tencentcloud/tuiroom-engine-js");
const basic = require("../stores/basic.js");
const room = require("../stores/room.js");
const chat = require("../stores/chat.js");
const useDeviceManager = require("../hooks/useDeviceManager.js");
const index$1 = require("../utils/common/logger/index.js");
const environment = require("../utils/environment.js");
const index = require("../locales/index.js");
const message = require("../constants/message.js");
const componentManager = require("./manager/componentManager.js");
const configManager = require("./manager/configManager.js");
const userManager = require("./manager/userManager.js");
const lifeCycleManager = require("./manager/lifeCycleManager.js");
const MediaManager = require("./manager/MediaManager.js");
const roomActionManager = require("./manager/roomActionManager.js");
const waterMark = require("./function/waterMark.js");
const virtualBackground = require("./function/virtualBackground.js");
const basicBeauty = require("./function/basicBeauty.js");
const scheduleConferenceManager = require("./manager/scheduleConferenceManager.js");
const conferenceInvitationManager = require("./manager/conferenceInvitationManager.js");
const errorHandler = require("./function/errorHandler.js");
const chatManager = require("./manager/chatManager.js");
const TUICore = require("@tencentcloud/tui-core");
const { t } = index.default.global;
const logPrefix = "[RoomService]";
const roomEngine = useRoomEngine.default();
const _RoomService = class _RoomService {
  constructor() {
    __publicField(this, "emitter", mitt());
    __publicField(this, "componentManager", new componentManager.ComponentManager(this));
    __publicField(this, "configManager", new configManager.ConfigManager(this));
    __publicField(this, "userManager", new userManager.UserManager(this));
    __publicField(this, "mediaManager", new MediaManager.MediaManager(this));
    __publicField(this, "lifeCycleManager", new lifeCycleManager.LifeCycleManager(this));
    __publicField(this, "roomActionManager", new roomActionManager.RoomActionManager(this));
    __publicField(this, "waterMark", new waterMark.WaterMark(this));
    __publicField(this, "virtualBackground", new virtualBackground.VirtualBackground(this));
    __publicField(this, "basicBeauty", new basicBeauty.BasicBeauty(this));
    __publicField(this, "scheduleConferenceManager", new scheduleConferenceManager.ScheduleConferenceManager(this));
    __publicField(this, "conferenceInvitationManager", new conferenceInvitationManager.ConferenceInvitationManager(this));
    __publicField(this, "errorHandler", new errorHandler.ErrorHandler(this));
    __publicField(this, "chatManager", new chatManager.ChatManager(this));
    __publicField(this, "roomEngine", roomEngine);
    __publicField(this, "t", t);
    this.lifeCycleManager.start();
    this.initEventCtx();
    TUIRoomEngine.once("ready", () => {
      this.bindRoomEngineEvents();
      this.handleRoomEngineReady();
      this.emit(types.EventType.SERVICE_READY);
    });
  }
  get basicStore() {
    return basic.useBasicStore();
  }
  get roomStore() {
    return room.useRoomStore();
  }
  get chatStore() {
    return chat.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.default({ listenForDeviceChange: true });
  }
  bindRoomEngineEvents() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
    (_a = roomEngine.instance) == null ? void 0 : _a.on(TUIRoomEngine.TUIRoomEvents.onError, this.onError);
    (_b = roomEngine.instance) == null ? void 0 : _b.on(
      TUIRoomEngine.TUIRoomEvents.onRoomDismissed,
      this.onRoomDismissed
    );
    (_c = roomEngine.instance) == null ? void 0 : _c.on(
      TUIRoomEngine.TUIRoomEvents.onUserVoiceVolumeChanged,
      this.onUserVoiceVolumeChanged
    );
    (_d = roomEngine.instance) == null ? void 0 : _d.on(
      TUIRoomEngine.TUIRoomEvents.onUserNetworkQualityChanged,
      this.onUserNetworkQualityChanged
    );
    (_e = roomEngine.instance) == null ? void 0 : _e.on(
      TUIRoomEngine.TUIRoomEvents.onKickedOutOfRoom,
      this.onKickedOutOfRoom
    );
    (_f = roomEngine.instance) == null ? void 0 : _f.on(
      TUIRoomEngine.TUIRoomEvents.onSendMessageForUserDisableChanged,
      this.onSendMessageForUserDisableChanged
    );
    (_g = roomEngine.instance) == null ? void 0 : _g.on(
      TUIRoomEngine.TUIRoomEvents.onUserSigExpired,
      this.onUserSigExpired
    );
    (_h = roomEngine.instance) == null ? void 0 : _h.on(
      TUIRoomEngine.TUIRoomEvents.onKickedOffLine,
      this.onKickedOffLine
    );
    (_i = roomEngine.instance) == null ? void 0 : _i.on(
      TUIRoomEngine.TUIRoomEvents.onAllUserCameraDisableChanged,
      this.onAllUserCameraDisableChanged
    );
    (_j = roomEngine.instance) == null ? void 0 : _j.on(
      TUIRoomEngine.TUIRoomEvents.onAllUserMicrophoneDisableChanged,
      this.onAllUserMicrophoneDisableChanged
    );
    (_k = roomEngine.instance) == null ? void 0 : _k.on(
      TUIRoomEngine.TUIRoomEvents.onScreenShareForAllUserDisableChanged,
      this.onScreenShareForAllUserDisableChanged
    );
    (_l = roomEngine.instance) == null ? void 0 : _l.on(
      TUIRoomEngine.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(TUIRoomEngine.TUIRoomEvents.onError, this.onError);
    (_b = roomEngine.instance) == null ? void 0 : _b.off(
      TUIRoomEngine.TUIRoomEvents.onRoomDismissed,
      this.onRoomDismissed
    );
    (_c = roomEngine.instance) == null ? void 0 : _c.off(
      TUIRoomEngine.TUIRoomEvents.onUserVoiceVolumeChanged,
      this.onUserVoiceVolumeChanged
    );
    (_d = roomEngine.instance) == null ? void 0 : _d.off(
      TUIRoomEngine.TUIRoomEvents.onUserNetworkQualityChanged,
      this.onUserNetworkQualityChanged
    );
    (_e = roomEngine.instance) == null ? void 0 : _e.off(
      TUIRoomEngine.TUIRoomEvents.onKickedOutOfRoom,
      this.onKickedOutOfRoom
    );
    (_f = roomEngine.instance) == null ? void 0 : _f.off(
      TUIRoomEngine.TUIRoomEvents.onSendMessageForUserDisableChanged,
      this.onSendMessageForUserDisableChanged
    );
    (_g = roomEngine.instance) == null ? void 0 : _g.off(
      TUIRoomEngine.TUIRoomEvents.onUserSigExpired,
      this.onUserSigExpired
    );
    (_h = roomEngine.instance) == null ? void 0 : _h.off(
      TUIRoomEngine.TUIRoomEvents.onKickedOffLine,
      this.onKickedOffLine
    );
    (_i = roomEngine.instance) == null ? void 0 : _i.off(
      TUIRoomEngine.TUIRoomEvents.onAllUserCameraDisableChanged,
      this.onAllUserCameraDisableChanged
    );
    (_j = roomEngine.instance) == null ? void 0 : _j.off(
      TUIRoomEngine.TUIRoomEvents.onAllUserMicrophoneDisableChanged,
      this.onAllUserMicrophoneDisableChanged
    );
    (_k = roomEngine.instance) == null ? void 0 : _k.off(
      TUIRoomEngine.TUIRoomEvents.onScreenShareForAllUserDisableChanged,
      this.onScreenShareForAllUserDisableChanged
    );
    (_l = roomEngine.instance) == null ? void 0 : _l.off(
      TUIRoomEngine.TUIRoomEvents.onUserInfoChanged,
      this.onUserInfoChanged
    );
  }
  onError(error) {
    index$1.default.error("roomEngine.onError: ", error);
    this.errorHandler.handleError(error, "onError");
  }
  onRoomDismissed(eventInfo) {
    const { roomId } = eventInfo;
    index$1.default.log(`${logPrefix}onRoomDismissed:`, roomId);
    this.emit(types.EventType.ROOM_NOTICE_MESSAGE_BOX, {
      title: t("Note"),
      message: t("The host closed the room."),
      confirmButtonText: t("Sure"),
      duration: 5e3,
      callback: async () => {
        this.emit(types.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: message2 } = eventInfo;
    try {
      let notice = "";
      switch (reason) {
        case TUIRoomEngine.TUIKickedOutOfRoomReason.kKickedByAdmin:
          notice = t("kicked out of the room by the host");
          break;
        case TUIRoomEngine.TUIKickedOutOfRoomReason.kKickedByLoggedOnOtherDevice:
          notice = t("kicked out of the room by other device");
          break;
        case TUIRoomEngine.TUIKickedOutOfRoomReason.kKickedByServer:
          notice = t("kicked out of the room by serve");
          break;
      }
      this.emit(types.EventType.ROOM_NOTICE_MESSAGE_BOX, {
        title: t("Note"),
        message: notice,
        confirmButtonText: t("Sure"),
        callback: async () => {
          this.emit(types.EventType.KICKED_OUT, { roomId, reason, message: message2 });
          this.resetStore();
        }
      });
    } catch (error) {
      index$1.default.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(types.EventType.ROOM_NOTICE_MESSAGE, {
        code: -1,
        type: "warning",
        message: tipMessage,
        duration: message.MESSAGE_DURATION.NORMAL
      });
      this.chatStore.setSendMessageDisableChanged(isDisable);
    }
    this.roomStore.setMuteUserChat(userId, isDisable);
  }
  onUserSigExpired() {
    this.emit(types.EventType.ROOM_NOTICE_MESSAGE_BOX, {
      title: t("Note"),
      message: t("userSig has expired"),
      confirmButtonText: t("Sure"),
      callback: () => {
        this.emit(types.EventType.USER_SIG_EXPIRED, {});
        this.resetStore();
      }
    });
  }
  onKickedOffLine(eventInfo) {
    const { message: message2 } = eventInfo;
    this.emit(types.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(types.EventType.KICKED_OFFLINE, { message: message2 });
      }
    });
  }
  async onAllUserCameraDisableChanged(eventInfo) {
    const { isDisable } = eventInfo;
    if (isDisable !== this.roomStore.isCameraDisableForAllUser && this.roomStore.localUser.userRole === TUIRoomEngine.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(types.EventType.ROOM_NOTICE_MESSAGE, {
      type: "success",
      message: tipMessage,
      duration: message.MESSAGE_DURATION.NORMAL
    });
    if (isDisableVideo && this.roomStore.localUser.userRole === TUIRoomEngine.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 === TUIRoomEngine.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(types.EventType.ROOM_NOTICE_MESSAGE, {
      type: "success",
      message: tipMessage,
      duration: message.MESSAGE_DURATION.NORMAL
    });
    if (isDisableAudio && this.roomStore.localUser.userRole === TUIRoomEngine.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;
    TUICore.TUILogin.login({
      SDKAppID: sdkAppId,
      userID: userId,
      userSig,
      useUploadPlugin: true
    });
    const { chat: chat2 } = TUICore.TUILogin.getContext();
    await TUIRoomEngine.login({ sdkAppId, userId, userSig, tim: chat2 });
    await TUIRoomEngine.setSelfInfo({ userName, avatarUrl });
    this.emit(types.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 = environment.isMobile ? TUIRoomEngine.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto : this.basicStore.isLocalStreamMirror ? TUIRoomEngine.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable : TUIRoomEngine.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable;
    await (trtcCloud == null ? void 0 : trtcCloud.setLocalRenderParams({
      mirrorType,
      rotation: TUIRoomEngine.TRTCVideoRotation.TRTCVideoRotation0,
      fillMode: TUIRoomEngine.TRTCVideoFillMode.TRTCVideoFillMode_Fill
    }));
  }
  logOut() {
    this.emit(types.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();
exports.RoomService = RoomService;
exports.roomEngine = roomEngine;
exports.roomService = roomService;
