<template>
  <Modal
    :open="visible"
    :title="$t('permission.title')"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <div class="permission-container">
      <div
        class="permission-item"
        v-for="permission in permissionsToShow"
        :key="permission"
      >
        <Checkbox v-model:checked="localPermissionSet[permission]">
          {{ $t(`permission.${permission}`) }}
        </Checkbox>
        <div class="permission-desc">
          {{ $t(`permission.${permission}Desc`) }}
        </div>
      </div>
    </div>
  </Modal>
</template>

<script setup lang="ts">
import { Modal, Checkbox } from "ant-design-vue";
import { computed, onMounted, ref, reactive } from "vue";
import { Permission } from "../utils/peer";
import { getPermissionSet, setPermissionSet } from "../utils/common";

const visible = ref(false);
const localPermissionSet = reactive({ ...getPermissionSet() });
const hasCamera = ref(false);
const permissionsToShow = computed(() =>
  Object.values(Permission).filter(
    (permission) => permission !== Permission.camera || hasCamera.value,
  ),
);

const checkCamera = async () => {
  try {
    const devices = await navigator.mediaDevices?.enumerateDevices?.();
    hasCamera.value =
      devices?.some((device) => device.kind === "videoinput") ?? false;
  } catch {
    hasCamera.value = false;
  }
};

const handleOk = () => {
  setPermissionSet(localPermissionSet);
  visible.value = false;
};

const handleCancel = () => {
  Object.assign(localPermissionSet, getPermissionSet());
  visible.value = false;
};

const showDialog = () => {
  checkCamera();
  visible.value = true;
};

onMounted(() => {
  checkCamera();
});

defineExpose({
  showDialog,
});
</script>

<style scoped>
.permission-container {
  padding: 10px 0;
}

.permission-item {
  margin-bottom: 20px;
}

.permission-desc {
  margin-left: 24px;
  color: #666;
  font-size: 12px;
}
</style>
