<template>
  <div></div>
</template>

<script setup>
import { defineEmits, computed, ref } from "vue";
import TRTC from "trtc-js-sdk";
import { useStore } from "vuex";
import { Dialog } from "@/global_components/";
import browser from "@/utils/browser";

const store = useStore();

const videoDeviceId = computed(() => store.getters["rtc/videoDeviceId"]);
const audioDeviceId = computed(() => store.getters["rtc/audioDeviceId"]);
const role = ref(browser.getURLParam("role"));

const emit = defineEmits(["switchDevice", "canUseDevice"]);

const updateDevice = async () => {
  console.log("updateDevice");
  const cameraItems = await TRTC.getCameras();
  cameraItems.forEach((item) => {
    item.value = item.deviceId;
  });
  const microphoneItems = await TRTC.getMicrophones();
  microphoneItems.forEach((item) => {
    item.value = item.deviceId;
  });

  store.commit("rtc/setDeviceList", {
    cameraList: cameraItems,
    microphoneList: microphoneItems,
  });

  if (!videoDeviceId.value) {
    if (cameraItems[0]) {
      store.commit("rtc/setVideoDeviceId", cameraItems[0].deviceId);
    } else {
      Dialog.toast({ content: `無法獲取您的攝像頭權限`, type: "error" });
    }
  }

  if (!audioDeviceId.value) {
    if (microphoneItems[0]) {
      store.commit("rtc/setAudioDeviceId", microphoneItems[0].deviceId);
    } else {
      Dialog.toast({ content: `無法獲取您的麥克風權限`, type: "error" });
    }
  }
};

let quxian = role.value == "leader" ?{ audio: true,video:true }: { audio: true };

console.log(quxian, '--------quxian-------');

navigator.mediaDevices
  .getUserMedia(quxian)
  .then((stream) => {
    stream.getTracks().forEach((track) => {
      track.stop();
    });
    updateDevice();
    emit("canUseDevice", true);
  })
  .catch((error) => {
    console.log(error, "error");
    Dialog.toast({ content: `請授權您的麥克風${role.value == "leader" ? "和攝像頭" : ""}權限`, type: "error" });
  });

navigator.mediaDevices.ondevicechange = updateDevice;

const handleDeviceChange = () => {
  emit("switchDevice", {
    videoId: store.videoDeviceId,
    audioId: store.audioDeviceId,
  });
};
</script>
