import { defineComponent, ref, watch, onBeforeUnmount, openBlock, createElementBlock, createElementVNode, toDisplayString, unref, createCommentVNode, createBlock, createVNode, withModifiers, withCtx, withDirectives, withKeys, vModelText, normalizeClass } from "vue";
import SvgIcon from "../../common/base/SvgIcon.vue.mjs";
import LoadingIcon from "../../common/icons/LoadingIcon.vue.mjs";
import NextIcon from "../../common/icons/NextIcon.vue.mjs";
import TuiButton from "../../common/base/Button.vue.mjs";
import useRoomControl from "./useRoomControlHooks.mjs";
import CreateRoomIcon from "../../common/icons/CreateRoomIcon.vue.mjs";
import EnterRoomIcon from "../../common/icons/EnterRoomIcon.vue.mjs";
import ScheduleRoomIcon from "../../common/icons/ScheduleRoomIcon.vue.mjs";
import useGetRoomEngine from "../../../hooks/useRoomEngine.mjs";
import { useBasicStore } from "../../../stores/basic.mjs";
import { useRoomStore } from "../../../stores/room.mjs";
import AudioMediaControl from "../../common/AudioMediaControl.vue.mjs";
import VideoMediaControl from "../../common/VideoMediaControl.vue.mjs";
import ScheduleConferencePanel from "../../ScheduleConference/ScheduleConferencePanel/index.mjs";
import TUIRoomEngine__default, { TUIRoomDeviceMangerEvents, TRTCVideoMirrorType, TRTCVideoRotation, TRTCVideoFillMode } from "@tencentcloud/tuiroom-engine-js";
import vClickOutside from "../../../directives/vClickOutside.mjs";
import { isEnumerateDevicesSupported, isGetUserMediaSupported } from "../../../utils/mediaAbility.mjs";
import useDeviceManager from "../../../hooks/useDeviceManager.mjs";
const _hoisted_1 = { class: "room-control-container" };
const _hoisted_2 = { class: "room-control-main" };
const _hoisted_3 = { class: "control-container" };
const _hoisted_4 = { class: "stream-preview-container" };
const _hoisted_5 = { class: "attention-info" };
const _hoisted_6 = {
  key: 0,
  class: "off-camera-info"
};
const _hoisted_7 = { class: "control-region" };
const _hoisted_8 = { class: "media-control-region" };
const _hoisted_9 = { class: "room-control-region" };
const _hoisted_10 = { class: "create-room-region" };
const _hoisted_11 = { class: "button-text" };
const _hoisted_12 = {
  key: 0,
  class: "create-room-items"
};
const _hoisted_13 = ["title"];
const _hoisted_14 = ["title"];
const _hoisted_15 = { class: "enter-room-region" };
const _hoisted_16 = { class: "button-text" };
const _hoisted_17 = {
  key: 1,
  class: "enter-room-action"
};
const _hoisted_18 = ["placeholder"];
const _hoisted_19 = {
  key: 0,
  class: "schedule-room-region"
};
const _hoisted_20 = { class: "button-text" };
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "RoomControlPC",
  props: {
    userName: { default: "" },
    showLogo: { type: Boolean, default: true },
    givenRoomId: {},
    enableScheduledConference: { type: Boolean, default: true }
  },
  emits: ["create-room", "enter-room"],
  setup(__props, { expose: __expose, emit: __emit }) {
    const roomStore = useRoomStore();
    const basicStore = useBasicStore();
    const { t } = useRoomControl();
    const { deviceManager, initMediaDeviceList } = useDeviceManager({
      listenForDeviceChange: true
    });
    const props = __props;
    __expose({
      getRoomParam,
      startStreamPreview
    });
    const roomEngine = useGetRoomEngine();
    const isCameraLoading = ref(false);
    const audioVolume = ref(0);
    const isMicMuted = ref(false);
    const isCameraMuted = ref(false);
    const showCreateRoomItems = ref(false);
    const showEnterRoomAction = ref(Boolean(props.givenRoomId));
    const scheduleConferenceDialogVisible = ref(false);
    const scheduleConference = () => {
      scheduleConferenceDialogVisible.value = true;
    };
    const tuiRoomParam = {
      isOpenCamera: true,
      isOpenMicrophone: true,
      defaultCameraId: "",
      defaultMicrophoneId: "",
      defaultSpeakerId: ""
    };
    async function openCamera() {
      var _a, _b;
      const trtcCloud = (_a = roomEngine.instance) == null ? void 0 : _a.getTRTCCloud();
      await (trtcCloud == null ? void 0 : trtcCloud.setLocalRenderParams({
        mirrorType: basicStore.isLocalStreamMirror ? TRTCVideoMirrorType.TRTCVideoMirrorType_Enable : TRTCVideoMirrorType.TRTCVideoMirrorType_Disable,
        rotation: TRTCVideoRotation.TRTCVideoRotation0,
        fillMode: TRTCVideoFillMode.TRTCVideoFillMode_Fill
      }));
      await ((_b = roomEngine.instance) == null ? void 0 : _b.startCameraDeviceTest({
        view: "stream-preview"
      }));
    }
    async function closeCamera() {
      var _a;
      await ((_a = roomEngine.instance) == null ? void 0 : _a.stopCameraDeviceTest());
    }
    async function openAudio() {
      var _a;
      await ((_a = roomEngine.instance) == null ? void 0 : _a.startMicDeviceTest({ interval: 200 }));
    }
    async function closeAudio() {
      var _a;
      await ((_a = roomEngine.instance) == null ? void 0 : _a.stopMicDeviceTest());
    }
    async function toggleMuteAudio() {
      isMicMuted.value = !isMicMuted.value;
      tuiRoomParam.isOpenMicrophone = !isMicMuted.value;
      if (isMicMuted.value) {
        await closeAudio();
        audioVolume.value = 0;
      } else {
        await openAudio();
      }
    }
    async function toggleMuteVideo() {
      isCameraMuted.value = !isCameraMuted.value;
      tuiRoomParam.isOpenCamera = !isCameraMuted.value;
      if (isCameraMuted.value) {
        await closeCamera();
        isCameraLoading.value = false;
      } else {
        isCameraLoading.value = true;
        await openCamera();
        isCameraLoading.value = false;
      }
    }
    function getRoomParam() {
      tuiRoomParam.defaultCameraId = roomStore.currentCameraId;
      tuiRoomParam.defaultMicrophoneId = roomStore.currentMicrophoneId;
      tuiRoomParam.defaultSpeakerId = roomStore.currentSpeakerId;
      return tuiRoomParam;
    }
    const onUserVoiceVolume = (options) => {
      audioVolume.value = options.volume;
    };
    async function startStreamPreview() {
      if (!isEnumerateDevicesSupported) {
        return;
      }
      isCameraLoading.value = true;
      await initMediaDeviceList();
      if (!isGetUserMediaSupported) {
        isCameraLoading.value = false;
        return;
      }
      if (roomStore.microphoneList && roomStore.microphoneList.length > 0) {
        openAudio();
      }
      if (roomStore.cameraList && roomStore.cameraList.length > 0) {
        await openCamera();
      }
      isCameraLoading.value = false;
    }
    const roomId = ref(props.givenRoomId);
    watch(
      () => props.givenRoomId,
      (val) => {
        roomId.value = val;
        showEnterRoomAction.value = Boolean(val);
      },
      { immediate: true }
    );
    const emit = __emit;
    function handleCreateRoom() {
      showCreateRoomItems.value = !showCreateRoomItems.value;
    }
    function handleClickOutsideCreateRoomItems() {
      if (showCreateRoomItems.value) {
        showCreateRoomItems.value = false;
      }
    }
    function handleEnterRoom() {
      showEnterRoomAction.value = true;
    }
    function createRoom(mode) {
      const roomParam = getRoomParam();
      emit("create-room", {
        roomMode: mode,
        roomParam,
        isSeatEnabled: Boolean(mode === "SpeakAfterTakingSeat")
      });
    }
    function enterRoom() {
      if (!roomId.value) {
        return;
      }
      const roomParam = getRoomParam();
      emit("enter-room", {
        roomId: String(roomId.value),
        roomParam
      });
    }
    TUIRoomEngine__default.once("ready", () => {
      var _a;
      startStreamPreview();
      (_a = deviceManager.instance) == null ? void 0 : _a.on(
        TUIRoomDeviceMangerEvents.onTestMicVolume,
        onUserVoiceVolume
      );
    });
    onBeforeUnmount(async () => {
      var _a;
      await closeAudio();
      await closeCamera();
      (_a = deviceManager.instance) == null ? void 0 : _a.off(
        TUIRoomDeviceMangerEvents.onTestMicVolume,
        onUserVoiceVolume
      );
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1, [
        createElementVNode("div", _hoisted_2, [
          createElementVNode("div", _hoisted_3, [
            createElementVNode("div", _hoisted_4, [
              _cache[4] || (_cache[4] = createElementVNode("div", {
                id: "stream-preview",
                class: "stream-preview"
              }, null, -1)),
              createElementVNode("div", _hoisted_5, [
                isCameraMuted.value ? (openBlock(), createElementBlock("span", _hoisted_6, toDisplayString(unref(t)("Off Camera")), 1)) : createCommentVNode("", true),
                isCameraLoading.value ? (openBlock(), createBlock(SvgIcon, {
                  key: 1,
                  icon: LoadingIcon,
                  class: "loading"
                })) : createCommentVNode("", true)
              ])
            ]),
            createElementVNode("div", _hoisted_7, [
              createElementVNode("div", _hoisted_8, [
                createVNode(AudioMediaControl, {
                  class: "media-control-item",
                  "has-more": true,
                  "is-muted": isMicMuted.value,
                  "audio-volume": audioVolume.value,
                  onClick: toggleMuteAudio
                }, null, 8, ["is-muted", "audio-volume"]),
                createVNode(VideoMediaControl, {
                  class: "media-control-item",
                  "has-more": true,
                  "is-muted": isCameraMuted.value,
                  onClick: toggleMuteVideo
                }, null, 8, ["is-muted"])
              ]),
              createElementVNode("div", _hoisted_9, [
                createElementVNode("div", _hoisted_10, [
                  createVNode(TuiButton, {
                    class: "button-item",
                    style: { "width": "170px" },
                    onClick: withModifiers(handleCreateRoom, ["stop"])
                  }, {
                    default: withCtx(() => [
                      createVNode(SvgIcon, { icon: CreateRoomIcon }),
                      createElementVNode("span", _hoisted_11, toDisplayString(unref(t)("New Room")), 1)
                    ]),
                    _: 1
                  }),
                  showCreateRoomItems.value ? withDirectives((openBlock(), createElementBlock("div", _hoisted_12, [
                    createElementVNode("div", {
                      class: "create-room-item",
                      onClick: _cache[0] || (_cache[0] = ($event) => createRoom("SpeakAfterTakingSeat"))
                    }, [
                      createElementVNode("span", {
                        title: unref(t)("On-stage Speaking Room"),
                        class: "create-room-option"
                      }, toDisplayString(unref(t)("On-stage Speaking Room")), 9, _hoisted_13),
                      createVNode(SvgIcon, {
                        class: "create-room-icon",
                        icon: NextIcon
                      })
                    ]),
                    createElementVNode("div", {
                      class: "create-room-item",
                      onClick: _cache[1] || (_cache[1] = ($event) => createRoom("FreeToSpeak"))
                    }, [
                      createElementVNode("span", {
                        title: unref(t)("Free Speech Room"),
                        class: "create-room-option"
                      }, toDisplayString(unref(t)("Free Speech Room")), 9, _hoisted_14),
                      createVNode(SvgIcon, {
                        class: "create-room-icon",
                        icon: NextIcon
                      })
                    ])
                  ])), [
                    [unref(vClickOutside), handleClickOutsideCreateRoomItems]
                  ]) : createCommentVNode("", true)
                ]),
                createElementVNode("div", _hoisted_15, [
                  !showEnterRoomAction.value ? (openBlock(), createBlock(TuiButton, {
                    key: 0,
                    class: "button-item",
                    style: { "width": "170px" },
                    onClick: handleEnterRoom
                  }, {
                    default: withCtx(() => [
                      createVNode(SvgIcon, { icon: EnterRoomIcon }),
                      createElementVNode("span", _hoisted_16, toDisplayString(unref(t)("Join Room")), 1)
                    ]),
                    _: 1
                  })) : createCommentVNode("", true),
                  showEnterRoomAction.value ? (openBlock(), createElementBlock("div", _hoisted_17, [
                    withDirectives(createElementVNode("input", {
                      "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => roomId.value = $event),
                      class: "input",
                      placeholder: unref(t)("Enter room ID"),
                      onKeyup: withKeys(enterRoom, ["enter"])
                    }, null, 40, _hoisted_18), [
                      [vModelText, roomId.value]
                    ]),
                    createElementVNode("div", {
                      class: normalizeClass([
                        "enter-button",
                        { active: roomId.value && roomId.value.length > 0 }
                      ]),
                      onClick: enterRoom
                    }, [
                      createVNode(SvgIcon, { icon: EnterRoomIcon })
                    ], 2)
                  ])) : createCommentVNode("", true)
                ]),
                props.enableScheduledConference ? (openBlock(), createElementBlock("div", _hoisted_19, [
                  createVNode(TuiButton, {
                    class: "button-item",
                    style: { "width": "170px" },
                    onClick: scheduleConference
                  }, {
                    default: withCtx(() => [
                      createVNode(SvgIcon, { icon: ScheduleRoomIcon }),
                      createElementVNode("span", _hoisted_20, toDisplayString(unref(t)("Schedule")), 1)
                    ]),
                    _: 1
                  })
                ])) : createCommentVNode("", true)
              ])
            ])
          ])
        ]),
        createVNode(unref(ScheduleConferencePanel), {
          visible: scheduleConferenceDialogVisible.value,
          "user-name": props.userName,
          onInput: _cache[3] || (_cache[3] = ($event) => scheduleConferenceDialogVisible.value = $event)
        }, null, 8, ["visible", "user-name"])
      ]);
    };
  }
});
export {
  _sfc_main as default
};
