import { defineComponent, ref, computed, watch, onUnmounted, unref, openBlock, createElementBlock, createVNode, withCtx, createBlock, createElementVNode, createTextVNode, toDisplayString, createCommentVNode } from "vue";
import { storeToRefs } from "pinia";
import renderMsg from "../../common/base/Message/Message.mjs";
import Dialog from "../../common/base/Dialog/index.mjs";
import IconButton from "../../common/base/IconButton.vue.mjs";
import ScreenShareIcon from "../../common/icons/ScreenShareIcon.vue.mjs";
import StopScreenShareIcon from "../../common/icons/StopScreenShareIcon.vue.mjs";
import TUIRoomEngine__default, { TUIRoomEvents } from "@tencentcloud/tuiroom-engine-js";
import useGetRoomEngine from "../../../hooks/useRoomEngine.mjs";
import { useRoomStore } from "../../../stores/room.mjs";
import { useBasicStore } from "../../../stores/basic.mjs";
import logger from "../../../utils/common/logger/index.mjs";
import { MESSAGE_DURATION } from "../../../constants/message.mjs";
import { useI18n } from "../../../locales/index.mjs";
import TuiButton from "../../common/base/Button.vue.mjs";
import bus from "../../../hooks/useMitt.mjs";
import { isScreenShareSupported } from "../../../utils/mediaAbility.mjs";
import "../../../services/main.mjs";
import { roomService } from "../../../services/roomService.mjs";
import "mitt";
import "../../../services/manager/roomActionManager.mjs";
import "@tencentcloud/tui-core";
const _hoisted_1 = {
  key: 0,
  class: "screen-share-control-container"
};
const logPrefix = "[ScreenShareControl]";
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "Index",
  setup(__props) {
    const roomEngine = useGetRoomEngine();
    const screenShareConfig = roomService.getComponentConfig("ScreenShare");
    const roomStore = useRoomStore();
    const basicStore = useBasicStore();
    const {
      isAnchor,
      isAudience,
      hasOtherScreenShare,
      isGeneralUser,
      isScreenShareDisableForAllUser
    } = storeToRefs(roomStore);
    const { isShowScreenShareAntiFraud } = storeToRefs(basicStore);
    const { t } = useI18n();
    const btnStopRef = ref();
    const isSharing = ref(false);
    const dialogVisible = ref(false);
    const isShowFraudDialog = ref(false);
    const screenShareDisabled = computed(() => isAudience.value);
    const title = computed(
      () => isSharing.value ? t("End sharing") : t("Share screen")
    );
    watch(isAnchor, (val, oldVal) => {
      if (!oldVal && val && isSharing.value) {
        stopScreenShare();
      }
    });
    async function toggleScreenShare() {
      if (isSharing.value) {
        dialogVisible.value = true;
        return;
      }
      if (isAudience.value) {
        renderMsg({
          type: "warning",
          message: t(
            "You currently do not have sharing permission, please raise your hand to apply for sharing permission first"
          ),
          duration: MESSAGE_DURATION.LONG
        });
        return;
      }
      if (hasOtherScreenShare.value) {
        renderMsg({
          type: "warning",
          message: t(
            "Another user is currently sharing the screen, screen sharing is not possible."
          ),
          duration: MESSAGE_DURATION.LONG
        });
        return;
      }
      if (!isScreenShareSupported) {
        renderMsg({
          type: "warning",
          message: t("The current browser does not support screen sharing"),
          duration: MESSAGE_DURATION.LONG
        });
        return;
      }
      if (isGeneralUser.value && isScreenShareDisableForAllUser.value) {
        renderMsg({
          type: "warning",
          message: t(
            "Failed to initiate screen sharing, currently only host/admin can share screen."
          ),
          duration: MESSAGE_DURATION.LONG
        });
        return;
      }
      if (!isShowScreenShareAntiFraud.value) {
        await startScreenShare();
        return;
      }
      isShowFraudDialog.value = true;
    }
    function cancelStop() {
      dialogVisible.value = false;
    }
    async function startScreenShare() {
      var _a;
      isShowFraudDialog.value = false;
      try {
        await ((_a = roomEngine.instance) == null ? void 0 : _a.startScreenSharing());
        isSharing.value = true;
      } catch (error) {
        logger.error(
          `${logPrefix}startScreenShare error:`,
          error.name,
          error.message,
          error.code
        );
        let message = "";
        switch (error.name) {
          case "NotReadableError":
            message = "The system prohibits the current browser from obtaining screen content";
            break;
          case "NotAllowedError":
            if (error.message.includes("Permission denied by system")) {
              message = "The system prohibits the current browser from obtaining screen content";
            } else {
              message = "User rejects/cancels screen sharing";
            }
            break;
          default:
            message = "Screen sharing encountered an unknown error";
            break;
        }
        renderMsg({
          type: "warning",
          message,
          duration: MESSAGE_DURATION.LONG
        });
      }
    }
    async function stopScreenShare() {
      var _a;
      if (isSharing.value) {
        try {
          await ((_a = roomEngine.instance) == null ? void 0 : _a.stopScreenSharing());
          dialogVisible.value = false;
          isSharing.value = false;
        } catch (error) {
          logger.error(`${logPrefix}stopScreenShare error:`, error);
        }
      }
    }
    function screenCaptureStopped() {
      isSharing.value = false;
    }
    bus.on("ScreenShare:stopScreenShare", stopScreenShare);
    TUIRoomEngine__default.once("ready", () => {
      var _a;
      (_a = roomEngine.instance) == null ? void 0 : _a.on(
        TUIRoomEvents.onUserScreenCaptureStopped,
        screenCaptureStopped
      );
    });
    onUnmounted(() => {
      var _a;
      bus.off("ScreenShare:stopScreenShare", stopScreenShare);
      (_a = roomEngine.instance) == null ? void 0 : _a.off(
        TUIRoomEvents.onUserScreenCaptureStopped,
        screenCaptureStopped
      );
    });
    return (_ctx, _cache) => {
      return unref(screenShareConfig).visible ? (openBlock(), createElementBlock("div", _hoisted_1, [
        createVNode(IconButton, {
          ref_key: "btnStopRef",
          ref: btnStopRef,
          "is-active": isSharing.value,
          disabled: screenShareDisabled.value,
          title: title.value,
          "is-not-support": !unref(isScreenShareSupported),
          onClickIcon: toggleScreenShare
        }, {
          default: withCtx(() => [
            isSharing.value ? (openBlock(), createBlock(StopScreenShareIcon, { key: 0 })) : (openBlock(), createBlock(ScreenShareIcon, { key: 1 }))
          ]),
          _: 1
        }, 8, ["is-active", "disabled", "title", "is-not-support"]),
        createVNode(unref(Dialog), {
          modelValue: isShowFraudDialog.value,
          "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => isShowFraudDialog.value = $event),
          width: "420px",
          title: unref(t)("Safety Reminder"),
          modal: true,
          "append-to-room-container": true
        }, {
          footer: withCtx(() => [
            createElementVNode("span", null, [
              createVNode(TuiButton, {
                size: "default",
                onClick: startScreenShare
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(unref(t)("Continue sharing")), 1)
                ]),
                _: 1
              }),
              createVNode(TuiButton, {
                class: "button",
                type: "primary",
                size: "default",
                onClick: _cache[0] || (_cache[0] = ($event) => isShowFraudDialog.value = false)
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(unref(t)("Cancel")), 1)
                ]),
                _: 1
              })
            ])
          ]),
          default: withCtx(() => [
            createElementVNode("span", null, toDisplayString(unref(t)(
              "Sharing screens may lead to the leakage of private information such as SMS verification codes and passwords, resulting in financial losses. Please be vigilant against various forms of fraud."
            )), 1)
          ]),
          _: 1
        }, 8, ["modelValue", "title"]),
        createVNode(unref(Dialog), {
          modelValue: dialogVisible.value,
          "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => dialogVisible.value = $event),
          width: "420px",
          title: unref(t)("End sharing"),
          modal: true,
          "before-close": cancelStop,
          "append-to-room-container": true
        }, {
          footer: withCtx(() => [
            createElementVNode("span", null, [
              createVNode(TuiButton, {
                size: "default",
                onClick: stopScreenShare
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(unref(t)("End sharing")), 1)
                ]),
                _: 1
              }),
              createVNode(TuiButton, {
                class: "button",
                type: "primary",
                size: "default",
                onClick: cancelStop
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(unref(t)("Cancel")), 1)
                ]),
                _: 1
              })
            ])
          ]),
          default: withCtx(() => [
            createElementVNode("span", null, toDisplayString(unref(t)(
              "Others will no longer see your screen after you stop sharing. Are you sure you want to stop?"
            )), 1)
          ]),
          _: 1
        }, 8, ["modelValue", "title"])
      ])) : createCommentVNode("", true);
    };
  }
});
export {
  _sfc_main as default
};
