"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const Vue = require("vue");
const environment = require("../../../utils/environment.js");
const IconButton = require("../../common/base/IconButton.vue.js");
const SvgIcon = require("../../common/base/SvgIcon.vue.js");
const StepDownIcon = require("../../common/icons/StepDownIcon.vue.js");
const ApplyStageIcon = require("../../common/icons/ApplyStageIcon.vue.js");
const CancelStageIcon = require("../../common/icons/CancelStageIcon.vue.js");
const CloseIcon = require("../../common/icons/CloseIcon.vue.js");
const index$2 = require("../../common/base/Dialog/index.js");
const Message = require("../../common/base/Message/Message.js");
const message = require("../../../constants/message.js");
const basic = require("../../../stores/basic.js");
const room = require("../../../stores/room.js");
const index = require("../../../locales/index.js");
const pinia = require("pinia");
const useRoomEngine = require("../../../hooks/useRoomEngine.js");
const index$1 = require("../../../utils/common/logger/index.js");
const TUIRoomEngine = require("@tencentcloud/tuiroom-engine-js");
const Button = require("../../common/base/Button.vue.js");
const utils = require("../../../utils/utils.js");
const _hoisted_1 = { class: "apply-control-container" };
const _hoisted_2 = {
  key: 0,
  class: "attention member-attention"
};
const _sfc_main = /* @__PURE__ */ Vue.defineComponent({
  __name: "MemberApplyControl",
  setup(__props) {
    const roomEngine = useRoomEngine.default();
    const { t } = index.useI18n();
    const basicStore = basic.useBasicStore();
    const roomStore = room.useRoomStore();
    const { lang } = pinia.storeToRefs(basicStore);
    const { localUser, isGeneralUser, isAdmin } = pinia.storeToRefs(roomStore);
    const isApplyingOnSeat = Vue.ref(false);
    const showMemberApplyAttention = Vue.ref(true);
    const iconName = Vue.ref();
    const iconTitle = Vue.ref("");
    const applyToAnchorRequestId = Vue.ref("");
    const inviteToAnchorRequestId = Vue.ref("");
    const showDialog = Vue.ref(false);
    const currentDialogTitle = Vue.ref("");
    const currentConfirmButton = Vue.ref("");
    const currentDialogType = Vue.ref("inviteDialog");
    Vue.watch(
      [localUser, isApplyingOnSeat, lang],
      ([localUser2, isApplyingOnSeat2]) => {
        if (localUser2.onSeat) {
          iconName.value = StepDownIcon.default;
          iconTitle.value = t("Step down");
          hideApplyAttention();
        } else {
          if (isApplyingOnSeat2) {
            iconName.value = CancelStageIcon.default;
            iconTitle.value = t("Cancel Apply");
          } else {
            iconName.value = ApplyStageIcon.default;
            iconTitle.value = t("Apply for the stage");
          }
        }
      },
      { immediate: true, deep: true }
    );
    const toggleApplySpeechDebounce = utils.debounce(toggleApplySpeech, 300);
    async function toggleApplySpeech() {
      hideApplyAttention();
      if (localUser.value.onSeat) {
        handleStepDownDialogVisible();
      } else {
        isApplyingOnSeat.value ? cancelSeatApplication() : sendSeatApplication();
      }
    }
    const inviteDialogInfo = {
      content: t("You can turn on the microphone and camera once you are on stage"),
      confirmButtonText: t("Agree to the stage"),
      cancelButtonText: t("Reject"),
      handleConfirm: () => handleInvite(true),
      handleCancel: () => handleInvite(false)
    };
    const leaveSeatDialogInfo = Vue.computed(() => ({
      content: localUser.value.userRole === TUIRoomEngine.TUIRole.kAdministrator ? t("To go on stage again, a new application needs to be initiated") : t(
        "To go on stage again, you need to reapply and wait for the roomOwner/administrator to approve"
      ),
      confirmButtonText: t("Step down"),
      cancelButtonText: t("Cancel"),
      handleConfirm: () => leaveSeat(),
      handleCancel: () => handleStepDownDialogVisible()
    }));
    const currentDialogInfo = Vue.computed(
      () => currentDialogType.value === "inviteDialog" ? inviteDialogInfo : leaveSeatDialogInfo.value
    );
    async function sendSeatApplication() {
      var _a, _b;
      if (isAdmin.value) {
        await ((_a = roomEngine.instance) == null ? void 0 : _a.takeSeat({ seatIndex: -1, timeout: 0 }));
        Message.default({ type: "success", message: t("Succeed on stage") });
        return;
      }
      if (isGeneralUser.value) {
        Message.default({
          type: "info",
          message: `${t("The request to go on stage has been sent out, please wait for the roomOwner/administrator to approve it")}`,
          duration: message.MESSAGE_DURATION.NORMAL
        });
      }
      const request = await ((_b = roomEngine.instance) == null ? void 0 : _b.takeSeat({
        seatIndex: -1,
        timeout: 60,
        requestCallback: (callbackInfo) => {
          isApplyingOnSeat.value = false;
          const { requestCallbackType } = callbackInfo;
          switch (requestCallbackType) {
            case TUIRoomEngine.TUIRequestCallbackType.kRequestAccepted:
              Message.default({ type: "success", message: t("Succeed on stage") });
              break;
            case TUIRoomEngine.TUIRequestCallbackType.kRequestRejected:
              Message.default({
                type: "warning",
                message: t("Application to go on stage was rejected")
              });
              break;
            case TUIRoomEngine.TUIRequestCallbackType.kRequestTimeout:
              Message.default({
                type: "warning",
                message: t("The request to go on stage has timed out")
              });
              break;
          }
        }
      }));
      if (request && request.requestId) {
        applyToAnchorRequestId.value = request.requestId;
      }
      isApplyingOnSeat.value = true;
    }
    async function cancelSeatApplication() {
      var _a;
      Message.default({
        type: "info",
        message: `${t("Canceled application to go on stage")}`,
        duration: message.MESSAGE_DURATION.NORMAL
      });
      try {
        await ((_a = roomEngine.instance) == null ? void 0 : _a.cancelRequest({
          requestId: applyToAnchorRequestId.value
        }));
        isApplyingOnSeat.value = false;
      } catch (error) {
        index$1.default.log("member cancelSpeechApplication", error);
      }
    }
    function handleStepDownDialogVisible() {
      showDialog.value = !showDialog.value;
      currentDialogType.value = "leaveSeatDialog";
      currentDialogTitle.value = t("Are you sure you want to step down");
    }
    async function leaveSeat() {
      var _a;
      await ((_a = roomEngine.instance) == null ? void 0 : _a.leaveSeat());
      showDialog.value = false;
      if (roomStore.isCameraDisableForAllUser && isGeneralUser.value) {
        roomStore.setCanControlSelfVideo(false);
      }
      if (roomStore.isMicrophoneDisableForAllUser && isGeneralUser.value) {
        roomStore.setCanControlSelfAudio(false);
      }
      basicStore.setIsOpenMic(false);
    }
    function hideApplyAttention() {
      showMemberApplyAttention.value = false;
    }
    async function onRequestReceived(eventInfo) {
      const {
        request: { userId, requestId, requestAction }
      } = eventInfo;
      if (requestAction === TUIRoomEngine.TUIRequestAction.kRequestRemoteUserOnSeat) {
        inviteToAnchorRequestId.value = requestId;
        const userRole = roomStore.getUserRole(userId) === TUIRoomEngine.TUIRole.kRoomOwner ? t("RoomOwner") : t("Admin");
        currentDialogTitle.value = t("Sb invites you to speak on stage", {
          role: userRole
        });
        currentConfirmButton.value = t("Agree to the stage");
        showDialog.value = true;
        currentDialogType.value = "inviteDialog";
      }
    }
    function onRequestCancelled(eventInfo) {
      const { requestId } = eventInfo;
      if (inviteToAnchorRequestId.value === requestId) {
        inviteToAnchorRequestId.value = "";
        showDialog.value = false;
      }
    }
    async function handleInvite(agree) {
      var _a;
      try {
        await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
          requestId: inviteToAnchorRequestId.value,
          agree
        }));
      } catch (error) {
        if (error.code === TUIRoomEngine.TUIErrorCode.ERR_ALL_SEAT_OCCUPIED) {
          Message.default({
            type: "warning",
            message: t("The stage is full, please contact the host")
          });
        } else {
          index$1.default.error(
            "Failure of a user to accept/reject a roomOwner invitation",
            error
          );
        }
      } finally {
        showDialog.value = false;
      }
    }
    async function onKickedOffSeat() {
      Message.default({
        type: "warning",
        message: t(
          "You have been invited by the host to step down, please raise your hand if you need to speak"
        ),
        duration: message.MESSAGE_DURATION.NORMAL
      });
    }
    TUIRoomEngine.once("ready", () => {
      var _a, _b, _c;
      (_a = roomEngine.instance) == null ? void 0 : _a.on(TUIRoomEngine.TUIRoomEvents.onRequestReceived, onRequestReceived);
      (_b = roomEngine.instance) == null ? void 0 : _b.on(TUIRoomEngine.TUIRoomEvents.onRequestCancelled, onRequestCancelled);
      (_c = roomEngine.instance) == null ? void 0 : _c.on(TUIRoomEngine.TUIRoomEvents.onKickedOffSeat, onKickedOffSeat);
    });
    Vue.onBeforeUnmount(() => {
      var _a, _b, _c;
      (_a = roomEngine.instance) == null ? void 0 : _a.off(TUIRoomEngine.TUIRoomEvents.onRequestReceived, onRequestReceived);
      (_b = roomEngine.instance) == null ? void 0 : _b.off(
        TUIRoomEngine.TUIRoomEvents.onRequestCancelled,
        onRequestCancelled
      );
      (_c = roomEngine.instance) == null ? void 0 : _c.off(TUIRoomEngine.TUIRoomEvents.onKickedOffSeat, onKickedOffSeat);
    });
    return (_ctx, _cache) => {
      return Vue.openBlock(), Vue.createElementBlock("div", null, [
        Vue.createElementVNode("div", _hoisted_1, [
          Vue.createVNode(IconButton.default, {
            title: iconTitle.value,
            icon: iconName.value,
            onClickIcon: Vue.unref(toggleApplySpeechDebounce)
          }, null, 8, ["title", "icon", "onClickIcon"]),
          showMemberApplyAttention.value ? (Vue.openBlock(), Vue.createElementBlock("div", _hoisted_2, [
            Vue.createElementVNode("span", {
              class: Vue.normalizeClass(Vue.unref(environment.isMobile) ? "mobile-info" : "info")
            }, Vue.toDisplayString(Vue.unref(t)("Please raise your hand to apply")), 3),
            Vue.createVNode(SvgIcon.default, {
              icon: CloseIcon.default,
              class: "close",
              onClick: hideApplyAttention
            })
          ])) : Vue.createCommentVNode("", true)
        ]),
        Vue.createVNode(Vue.unref(index$2.default), {
          modelValue: showDialog.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => showDialog.value = $event),
          title: currentDialogTitle.value,
          modal: true,
          "show-close": false,
          "close-on-click-modal": false,
          width: "500px",
          "append-to-room-container": true,
          "confirm-button": currentDialogInfo.value.confirmButtonText,
          "cancel-button": currentDialogInfo.value.cancelButtonText,
          onConfirm: currentDialogInfo.value.handleConfirm,
          onCancel: currentDialogInfo.value.handleCancel
        }, {
          footer: Vue.withCtx(() => [
            Vue.createVNode(Button.default, {
              size: "default",
              onClick: currentDialogInfo.value.handleConfirm
            }, {
              default: Vue.withCtx(() => [
                Vue.createTextVNode(Vue.toDisplayString(currentDialogInfo.value.confirmButtonText), 1)
              ]),
              _: 1
            }, 8, ["onClick"]),
            Vue.createVNode(Button.default, {
              class: "cancel-button",
              size: "default",
              type: "primary",
              onClick: currentDialogInfo.value.handleCancel
            }, {
              default: Vue.withCtx(() => [
                Vue.createTextVNode(Vue.toDisplayString(currentDialogInfo.value.cancelButtonText), 1)
              ]),
              _: 1
            }, 8, ["onClick"])
          ]),
          default: Vue.withCtx(() => [
            Vue.createElementVNode("span", null, Vue.toDisplayString(currentDialogInfo.value.content), 1)
          ]),
          _: 1
        }, 8, ["modelValue", "title", "confirm-button", "cancel-button", "onConfirm", "onCancel"])
      ]);
    };
  }
});
exports.default = _sfc_main;
