import { defineComponent, computed, ref, onUnmounted, openBlock, createElementBlock, createVNode, unref, withCtx, createTextVNode, toDisplayString, createElementVNode } from "vue";
import { storeToRefs } from "pinia";
import renderMsg from "../common/base/Message/Message.mjs";
import Dialog from "../common/base/Dialog/index.mjs";
import { useRoomStore } from "../../stores/room.mjs";
import { WARNING_MESSAGE, MESSAGE_DURATION } from "../../constants/message.mjs";
import { useI18n } from "../../locales/index.mjs";
import TUIRoomEngine__default, { TUIRoomEvents, TUIRequestAction, TUIRole } from "@tencentcloud/tuiroom-engine-js";
import useGetRoomEngine from "../../hooks/useRoomEngine.mjs";
import { isMobile, isWeChat } from "../../utils/environment.mjs";
import TuiButton from "../common/base/Button.vue.mjs";
import AudioMediaControl from "../common/AudioMediaControl.vue.mjs";
import { useBasicStore } from "../../stores/basic.mjs";
import MessageBox from "../common/base/MessageBox/index.mjs";
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "AudioControl",
  emits: ["click"],
  setup(__props, { emit: __emit }) {
    const roomEngine = useGetRoomEngine();
    const roomStore = useRoomStore();
    const basicStore = useBasicStore();
    const {
      isAudience,
      localUser,
      isLocalAudioIconDisable,
      isMicrophoneDisableForAllUser,
      userVolumeObj
    } = storeToRefs(roomStore);
    const emits = __emit;
    const hasMore = computed(() => !isMobile);
    const { t } = useI18n();
    const dialogContent = ref("");
    function handleAudioMediaClick() {
      emits("click");
      toggleMuteAudio();
    }
    async function toggleMuteAudio() {
      var _a, _b, _c, _d;
      if (isLocalAudioIconDisable.value) {
        let warningMessage = "";
        if (isAudience.value) {
          warningMessage = WARNING_MESSAGE.UNMUTE_LOCAL_MIC_FAIL_AUDIENCE;
        } else if (isMicrophoneDisableForAllUser.value) {
          warningMessage = WARNING_MESSAGE.UNMUTE_LOCAL_MIC_FAIL_MUTE_ALL;
        }
        renderMsg({
          type: "warning",
          message: t(warningMessage),
          duration: MESSAGE_DURATION.NORMAL
        });
        return;
      }
      if (localUser.value.hasAudioStream) {
        await ((_a = roomEngine.instance) == null ? void 0 : _a.muteLocalAudio());
        if (roomStore.isMicrophoneDisableForAllUser) {
          roomStore.setCanControlSelfAudio(false);
        }
      } else {
        const microphoneList = await ((_b = roomEngine.instance) == null ? void 0 : _b.getMicDevicesList());
        const hasMicrophoneDevice = microphoneList.length > 0;
        if (!hasMicrophoneDevice && !isWeChat) {
          MessageBox({
            title: t("Note"),
            message: t("Microphone not detected on current device"),
            confirmButtonText: t("Sure")
          });
          return;
        }
        await ((_c = roomEngine.instance) == null ? void 0 : _c.unmuteLocalAudio());
        if (!basicStore.isOpenMic) {
          (_d = roomEngine.instance) == null ? void 0 : _d.openLocalMicrophone();
          basicStore.setIsOpenMic(true);
        }
      }
    }
    const showRequestOpenMicDialog = ref(false);
    const requestOpenMicRequestId = ref("");
    async function onRequestReceived(eventInfo) {
      const { userId, requestAction, requestId } = eventInfo.request;
      if (requestAction === TUIRequestAction.kRequestToOpenRemoteMicrophone) {
        const userRole = roomStore.getUserRole(userId) === TUIRole.kRoomOwner ? t("RoomOwner") : t("Admin");
        dialogContent.value = t("Sb invites you to turn on the microphone", {
          role: userRole
        });
        requestOpenMicRequestId.value = requestId;
        showRequestOpenMicDialog.value = true;
      }
    }
    async function handleAccept() {
      var _a;
      roomStore.setCanControlSelfAudio(true);
      await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
        requestId: requestOpenMicRequestId.value,
        agree: true
      }));
      requestOpenMicRequestId.value = "";
      showRequestOpenMicDialog.value = false;
    }
    async function handleReject() {
      var _a;
      await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
        requestId: requestOpenMicRequestId.value,
        agree: false
      }));
      requestOpenMicRequestId.value = "";
      showRequestOpenMicDialog.value = false;
    }
    async function onRequestCancelled(eventInfo) {
      const { requestId } = eventInfo;
      if (requestOpenMicRequestId.value === requestId) {
        showRequestOpenMicDialog.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(AudioMediaControl, {
          "has-more": hasMore.value,
          "is-muted": !unref(localUser).hasAudioStream,
          "is-disabled": unref(isLocalAudioIconDisable),
          "audio-volume": unref(userVolumeObj)[unref(localUser).userId],
          onClick: handleAudioMediaClick
        }, null, 8, ["has-more", "is-muted", "is-disabled", "audio-volume"]),
        createVNode(unref(Dialog), {
          modelValue: showRequestOpenMicDialog.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => showRequestOpenMicDialog.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 microphone"),
          "cancel-button": unref(t)("Keep it closed"),
          onConfirm: handleAccept,
          onCancel: handleReject
        }, {
          footer: withCtx(() => [
            createVNode(TuiButton, {
              class: "agree-button",
              size: "default",
              onClick: handleAccept
            }, {
              default: withCtx(() => [
                createTextVNode(toDisplayString(unref(t)("Turn on the microphone")), 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
};
