<script setup lang="ts">
import { useGLTF, Text3D } from '@tresjs/cientos'
import { DoubleSide, Vector3 } from 'three';
const props = defineProps(['modelUrl', 'model', 'position', 'target', 'parent'])

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) : null)

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 => {
            if (target.value) {
                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
                    }
                    if (model.value !== undefined && model.value[element.func] !== undefined && model.value.__tres) {
                        try {
                            model.value[element.func](step)
                        } catch (error) {
                            console.log('lvl 1')
                            try { model.value[element.func](step) } catch {
                                console.log('lvl 2')
                                try { model.value[element.func](step) } catch {
                                    console.log('lvl 3')
                                }
                            }
                        }
                    }
                }
            }
        });
    }
})

watch(props, () => {
    if (props.target) {
        target.value = new Vector3(...props.target)
    }
}, { deep: true })
</script>
<template>
    <template v-if="scene.children[0]">
        <TresGroup ref="model" :name="scene.children[0].name">
            <Suspense>
                <primitive :object="scene.children[0]" :position="(props.position || [0, 0, 0])" />
            </Suspense>
            <Suspense v-if="false">
                <Text3D :text="scene.children[0].name"
                    font='https://raw.githubusercontent.com/Tresjs/assets/main/fonts/FiraCodeRegular.json'>
                    <TresMeshNormalMaterial color=red />
                </Text3D>
            </Suspense>
        </TresGroup>
    </template>
</template>