<script setup lang="ts">
import { ref } from 'vue';
import { useLoop, useTresContext } from '@tresjs/core';
// @ts-ignore 
import { useGLTF } from '@tresjs/cientos';
import { OrbitControlsProps } from '@tresjs/cientos/dist/core/controls/OrbitControls.vue.js';
import { useRawData } from '../../stores/raw_data';
import { IMAGE_URL } from '../../constants';

const { controls, camera } = useTresContext()
const raw_dataStore = useRawData()
const models = ref([] as model3DType[])
const envVars = ref({} as any)

const loadModels = async () => {
    envVars.value = Object.assign(envVars.value, raw_dataStore.data.env)
    for (let index = 0; index < raw_dataStore.data.elements.length; index++) {
        const element = raw_dataStore.data.elements[index];
        const item = {} as model3DType

        if (element.name == 'ground') continue

        item.modelUrl = `${IMAGE_URL}/${element.model_file}`
        let { scene: loaded_scene } = await useGLTF(item.modelUrl)
        item.modelFile = loaded_scene
        item.id = element.id
        item.name = element.name

        if (!element.is_enabled) {
            item.modelFile.visible = false
        }

        if (item.modelFile.children[0]) {
            item.modelFile.children[0].position.set(
                item.modelFile.children[0].position.x + element.x_pos,
                item.modelFile.children[0].position.y + element.y_pos,
                item.modelFile.children[0].position.z + element.z_pos
            )
            item.modelFile.children[0].updateMatrixWorld(true)
        }
        models.value.push(item)
    }
    rotateSet()
}
const cameraSet = () => {
    if (controls.value) {
        (controls.value as OrbitControlsProps).minDistance = raw_dataStore.data.min_distance;
        (controls.value as OrbitControlsProps).maxDistance = raw_dataStore.data.max_distance;
        // (controls.value as OrbitControlsProps).autoRotate = true;
        // (controls.value as OrbitControlsProps).autoRotateSpeed = 0.5;
        (controls.value as any).update()
    }
    if (camera.value) {
        const d = raw_dataStore.data.max_distance * 0.75;
        camera.value.position.set(d * 0.25, d, d);
        camera.value.updateMatrixWorld()
    }
}
const rotateSet = () => {
    if (controls.value) {
        (controls.value as OrbitControlsProps).autoRotate = true;
        (controls.value as OrbitControlsProps).autoRotateSpeed = 0.5;
    }
}
cameraSet()
loadModels()
const { onAfterRender } = useLoop()
onAfterRender(() => {
    if (controls.value) {
        if (!(controls.value as OrbitControlsProps).autoRotate) {
            rotateSet()
        }
        (controls.value as any).update()
    }
})
</script>
<template>
    <Env v-bind="envVars" />
    <template v-for="item in models">
        <TresGroup :name="item.name">
            <TresObject3D v-bind="item.modelFile.clone()" />
        </TresGroup>
    </template>
</template>