<script setup lang="ts">
import { useGLTF } from '@tresjs/cientos'
import { Box3, Color, MeshStandardMaterial, Vector3 } from 'three';
const props = defineProps(['modelUrl', 'model', 'position', 'removePos', 'target', 'color', 'map'])

let scene: any
if (props.modelUrl) {
    const { scene: model } = await useGLTF(props.modelUrl, { draco: true })
    scene = model
} else {
    scene = props.model
}
scene.receiveShadow = true
scene.castShadow = true

const target = ref(props.target ? new Vector3(...props.target) : new Vector3(0, 0, 0))

function shadows_and_pos(scene: any) {
    scene.children.forEach((el: any) => {
        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', },
]
type vectorType = 'x' | 'y' | 'z';

onLoop(() => {
    if (model.value && target.value) {
        axis.forEach(element => {
            const point = model.value.position[element.axis]
            let step = stepbase * target.value[element.axis as vectorType]
            if (step !== 0) {
                if (Math.abs(point) >= Math.abs(target.value[element.axis as vectorType])) {
                    step = 0
                }
                model.value[element.func](step)
            }
        });
    }
})

watch(props, () => {
    if (props.target) {
        target.value = new Vector3(...props.target)
    }
}, { deep: true })

</script>
<template>
    <Suspense>
        <TresGroup :position="(props.position || [0, 0, 0])" ref="model">
            <primitive :object="scene.children[0]" />
        </TresGroup>
    </Suspense>
</template>