<template>
  <canvas
    id="canvas"
    ref="canvas"
    width="100%"
    height="100%"
  ></canvas>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useViewer3cr } from '@/composables/useViewer3cr';
import { InteractivityState } from '@3cr/types-ts';
import { storeToRefs } from 'pinia';
import { useViewerStore } from '@/stores/viewer.store';
import { useNavigationCube } from '@/composables/useNavigationCube';

type Emits = {
  loaded: [void];
};

const emit = defineEmits<Emits>();

const viewer3cr = useViewer3cr();
const { enableMouse, enableKeyboard, options } = storeToRefs(useViewerStore());

const canvas = ref<HTMLCanvasElement>();
useNavigationCube(canvas);

/* v8 ignore start -- @preserve */
watch(enableMouse, async (value: boolean) => {
  const message: InteractivityState = { Version: '0.0.0', Value: value };
  await viewer3cr.setMouseInput({ message });
});

watch(enableKeyboard, async (value: boolean) => {
  const message: InteractivityState = { Version: '0.0.0', Value: value };
  await viewer3cr.setKeyboardInput({ message });
});
/* v8 ignore stop -- @preserve */

onMounted(async () => {
  if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
    // Mobile device style: fill the whole browser client area with the game canvas:
    const meta = document.createElement('meta');
    meta.name = 'viewport';
    meta.content =
      'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
    document.head.appendChild(meta);
  }

  if (navigator.storage && navigator.storage.estimate) {
    const quota = await navigator.storage.estimate();
    const percentageUsed = (quota.usage! / quota.quota!) * 100;
    console.log(`You've used ${percentageUsed}% of the available storage.`);
    const remaining = quota.quota! - quota.usage!;
    console.log(`You can write up to ${remaining} more bytes.`);
  }

  await viewer3cr.register(canvas.value!);
  /* v8 ignore start -- @preserve */
  if (options.value.onViewerLoaded) {
    await options.value.onViewerLoaded(viewer3cr);
  }
  /* v8 ignore stop -- @preserve */

  emit('loaded');
});

defineExpose({ canvas });
</script>
