<script setup>

import { ref, useTemplateRef, onMounted } from 'vue';
import Button from '../components/Button.vue';
import MainLayout from '../components/MainLayout.vue';
import TopBar from '../components/TopBar.vue';
import utils from '../utils.js';
import { EmbeddedViewer, RGBAColor, RGBColor, EdgeSettings } from 'online-3d-viewer';

const emits = defineEmits([ 'close' ]);
const props = defineProps({
  tr: {
    type: Function,
    default(id) { console.warn('Missing tr for ThreeDViewer'); return utils.translation(id); }
  }
});

const entry = ref(null);
const container = useTemplateRef('container');

const SUPPORTED_EXTENSIONS = [
  '3dm', '3ds', '3mf', 'amf', 'bim', 'brep',
  'dae', 'fbx', 'fcstd', 'glb', 'gltf',
  'ifc', 'igs', 'iges', 'stp', 'step',
  'stl', 'obj', 'off', 'ply', 'wrl',
];

function canHandle(e) {
  return SUPPORTED_EXTENSIONS.includes(e.extension.toLowerCase());
}

let viewer;

async function open(e, content) {
  if (!e || e.isDirectory || !canHandle(e)) return;

  entry.value = e;

  viewer.LoadModelFromFileList([ new File([content], e.fileName) ], {
    onModelLoaded: () => viewer.Resize()
  });

  // setTimeout(() => viewer.Resize(), 1000);
}

function onClose() {
  emits('close');
}

onMounted(() => {
  viewer = new EmbeddedViewer(container.value, {
    backgroundColor: new RGBAColor(59, 68, 76, 0),
    defaultColor: new RGBColor(65, 131, 196),
    edgeSettings: new EdgeSettings(false, new RGBColor(0, 0, 0), 1),
  });

  const resizeObserver = new ResizeObserver((entries) => {
    viewer.Resize();
  });

  resizeObserver.observe(container.value);
});

defineExpose({
  canHandle,
  open,
});

</script>

<template>
  <MainLayout :gap="false" class="main-layout">
    <template #header>
      <TopBar class="navbar" :gap="false">
        <template #left>
        </template>
        <template #center>
          <div class="file-name">{{ entry ? entry.fileName : '' }}</div>
        </template>
        <template #right>
          <Button icon="fa-solid fa-xmark" @click="onClose">{{ tr('main.dialog.close') }}</Button>
        </template>
      </TopBar>
    </template>
    <template #body>
      <div ref="container" class="threed-object-container"></div>
    </template>
  </MainLayout>
</template>

<style scoped>

.threed-object-container {
  width: 100%;
  height: 100%;
}

.main-layout {
  background-color: white;
}

</style>
