<script setup lang="ts">
import { useGLTF } from '@tresjs/cientos'
import { Box3, Vector3 } from 'three';
const props = defineProps(['modelUrl', 'position', 'removePos', 'target'])
const { scene } = await useGLTF(props.modelUrl)
scene.receiveShadow = true
scene.castShadow = true

const target = props.target ? new Vector3(...props.target) : new Vector3(0, 0, 0)
const box = new Box3();
box.expandByObject(scene.children[0]);
let size = new Vector3();
box.getSize(size)
// const box_size = [size.x, size.y, size.z]

scene.children.forEach((el: any) => {
    el.castShadow = true
    el.receiveShadow = true
    if (props.removePos) {
        el.translateX(-el.position.x)
        el.translateY(-el.position.y)
        el.translateZ(-el.position.z)
    }
});

function shadows_and_pos(scene: any) {
    scene.children.forEach((el: any) => {
        el.castShadow = true
        el.receiveShadow = true
        if (props.removePos) {
            el.translateX(-el.position.x)
            el.translateY(-el.position.y)
            el.translateZ(-el.position.z)
        }
        shadows_and_pos(el)
    })
}

shadows_and_pos(scene)

const model = ref()
const { onLoop } = useRenderLoop()
let stepbase = 0.005
const axis = [
    { axis: 'x', func: 'translateX', },
    { axis: 'y', func: 'translateY', },
    { axis: 'z', func: 'translateZ', },
]
onLoop(() => {
    if (model.value && props.target) {
        axis.forEach(element => {
            const point = model.value.position[element.axis]
            let step = stepbase * target[element.axis]
            if (Math.abs(point) >= Math.abs(target[element.axis])) {
                step = 0
            }
            model.value[element.func](step)
        });
    }
})
</script>
<template>
    <TresGroup :position="props.position || [0, 0, 0]" ref="model">
        <primitive :object="scene" cast-shadow receive-shadow />
    </TresGroup>
</template>