import { defineComponent, ref, computed, onUnmounted, openBlock, createElementBlock, createVNode, unref, withCtx, createTextVNode, toDisplayString, createElementVNode } from "vue";
import { storeToRefs } from "pinia";
import Dialog from "../common/base/Dialog/index.mjs";
import VideoMediaControl from "../common/VideoMediaControl.vue.mjs";
import { useRoomStore } from "../../stores/room.mjs";
import { WARNING_MESSAGE, MESSAGE_DURATION } from "../../constants/message.mjs";
import { useI18n } from "../../locales/index.mjs";
import useGetRoomEngine from "../../hooks/useRoomEngine.mjs";
import useDeviceManager from "../../hooks/useDeviceManager.mjs";
import TUIRoomEngine__default, { TUIRoomEvents, TUIMediaDeviceType, TUIRequestAction, TUIRole } from "@tencentcloud/tuiroom-engine-js";
import { isMobile, isWeChat } from "../../utils/environment.mjs";
import { useBasicStore } from "../../stores/basic.mjs";
import TuiButton from "../common/base/Button.vue.mjs";
import renderMsg from "../common/base/Message/Message.mjs";
import MessageBox from "../common/base/MessageBox/index.mjs";
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "VideoControl",
  emits: ["click"],
  setup(__props, { emit: __emit }) {
    const roomEngine = useGetRoomEngine();
    const { deviceManager } = useDeviceManager();
    const roomStore = useRoomStore();
    const basicStore = useBasicStore();
    const dialogContent = ref("");
    const emits = __emit;
    const {
      isCameraDisableForAllUser,
      isAudience,
      localUser,
      isLocalVideoIconDisable
    } = storeToRefs(roomStore);
    const { t } = useI18n();
    const hasMore = computed(() => !isMobile);
    const showVideoSettingTab = ref(false);
    function handleVideoMediaClick() {
      emits("click");
      toggleMuteVideo();
    }
    async function toggleMuteVideo() {
      var _a, _b, _c, _d;
      if (isLocalVideoIconDisable.value) {
        let warningMessage = "";
        if (isAudience.value) {
          warningMessage = WARNING_MESSAGE.UNMUTE_LOCAL_CAMERA_FAIL_AUDIENCE;
        } else if (isCameraDisableForAllUser.value) {
          warningMessage = WARNING_MESSAGE.UNMUTE_LOCAL_CAMERA_FAIL_MUTE_ALL;
        }
        renderMsg({
          type: "warning",
          message: t(warningMessage),
          duration: MESSAGE_DURATION.NORMAL
        });
        return;
      }
      if (localUser.value.hasVideoStream) {
        await ((_a = roomEngine.instance) == null ? void 0 : _a.closeLocalCamera());
        if (roomStore.isCameraDisableForAllUser) {
          roomStore.setCanControlSelfVideo(false);
        }
      } else {
        const cameraList = await ((_b = deviceManager.instance) == null ? void 0 : _b.getDevicesList({
          type: TUIMediaDeviceType.kMediaDeviceTypeVideoCamera
        }));
        const hasCameraDevice = cameraList && cameraList.length > 0;
        if (!hasCameraDevice && !isWeChat) {
          MessageBox({
            title: t("Note"),
            message: t("Camera not detected on current device"),
            confirmButtonText: t("Sure")
          });
          return;
        }
        if (isMobile) {
          await ((_c = roomEngine.instance) == null ? void 0 : _c.openLocalCamera({
            isFrontCamera: basicStore.isFrontCamera
          }));
        } else {
          await ((_d = roomEngine.instance) == null ? void 0 : _d.openLocalCamera());
        }
      }
      showVideoSettingTab.value = false;
    }
    const showRequestOpenCameraDialog = ref(false);
    const requestOpenCameraRequestId = ref("");
    async function onRequestReceived(eventInfo) {
      const { userId, requestAction, requestId } = eventInfo.request;
      if (requestAction === TUIRequestAction.kRequestToOpenRemoteCamera) {
        const userRole = roomStore.getUserRole(userId) === TUIRole.kRoomOwner ? t("RoomOwner") : t("Admin");
        dialogContent.value = t("Sb invites you to turn on the camera", {
          role: userRole
        });
        requestOpenCameraRequestId.value = requestId;
        showRequestOpenCameraDialog.value = true;
      }
    }
    async function handleAccept() {
      var _a;
      roomStore.setCanControlSelfVideo(true);
      await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
        requestId: requestOpenCameraRequestId.value,
        agree: true
      }));
      requestOpenCameraRequestId.value = "";
      showRequestOpenCameraDialog.value = false;
    }
    async function handleReject() {
      var _a;
      await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
        requestId: requestOpenCameraRequestId.value,
        agree: false
      }));
      requestOpenCameraRequestId.value = "";
      showRequestOpenCameraDialog.value = false;
    }
    async function onRequestCancelled(eventInfo) {
      const { requestId } = eventInfo;
      if (requestOpenCameraRequestId.value === requestId) {
        showRequestOpenCameraDialog.value = false;
      }
    }
    TUIRoomEngine__default.once("ready", () => {
      var _a, _b;
      (_a = roomEngine.instance) == null ? void 0 : _a.on(TUIRoomEvents.onRequestReceived, onRequestReceived);
      (_b = roomEngine.instance) == null ? void 0 : _b.on(TUIRoomEvents.onRequestCancelled, onRequestCancelled);
    });
    onUnmounted(() => {
      var _a, _b;
      (_a = roomEngine.instance) == null ? void 0 : _a.off(TUIRoomEvents.onRequestReceived, onRequestReceived);
      (_b = roomEngine.instance) == null ? void 0 : _b.off(
        TUIRoomEvents.onRequestCancelled,
        onRequestCancelled
      );
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", null, [
        createVNode(VideoMediaControl, {
          "has-more": hasMore.value,
          "is-muted": !unref(localUser).hasVideoStream,
          "is-disabled": unref(isLocalVideoIconDisable),
          onClick: handleVideoMediaClick
        }, null, 8, ["has-more", "is-muted", "is-disabled"]),
        createVNode(unref(Dialog), {
          modelValue: showRequestOpenCameraDialog.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => showRequestOpenCameraDialog.value = $event),
          title: unref(t)("Tips"),
          modal: true,
          "show-close": false,
          "close-on-click-modal": false,
          width: "500px",
          "append-to-room-container": true,
          "confirm-button": unref(t)("Turn on the camera"),
          "cancel-button": unref(t)("Keep it closed"),
          onConfirm: handleAccept,
          onCancel: handleReject
        }, {
          footer: withCtx(() => [
            createVNode(TuiButton, {
              class: "cancel-button",
              size: "default",
              onClick: handleAccept
            }, {
              default: withCtx(() => [
                createTextVNode(toDisplayString(unref(t)("Turn on the camera")), 1)
              ]),
              _: 1
            }),
            createVNode(TuiButton, {
              class: "cancel-button",
              size: "default",
              type: "primary",
              onClick: handleReject
            }, {
              default: withCtx(() => [
                createTextVNode(toDisplayString(unref(t)("Keep it closed")), 1)
              ]),
              _: 1
            })
          ]),
          default: withCtx(() => [
            createElementVNode("span", null, toDisplayString(dialogContent.value), 1)
          ]),
          _: 1
        }, 8, ["modelValue", "title", "confirm-button", "cancel-button"])
      ]);
    };
  }
});
export {
  _sfc_main as default
};
