<script setup lang="ts">
import { Box3, Vector3 } from 'three';
import { degToRad } from 'three/src/math/MathUtils.js';

const props = defineProps(['number', 'count', 'models'])
const rotate = () => {
    switch (props.number) {
        case 1:
            return degToRad(0)
        case 2:
            return degToRad(90)
        case 3:
            return degToRad(180)
        case 4:
            return degToRad(270)
    }
}
const { seekByName } = useSeek()
const { scene } = useTresContext()

const section_count = use_section_count()
const extra_section = use_extra_section()

const size = ref(new Vector3())
const position = ref(new Vector3())
const total = ref((section_count.value + ~~(!!extra_section.value)))

const count_pos = () => {
    total.value = (section_count.value + ~~(!!extra_section.value))

    const line = seekByName(scene.value, `line_${props.number}`)
    const ssize = new Vector3()
    if (line && line.children.length) {
        line.updateMatrixWorld()
        const bbox = new Box3()
        bbox.expandByObject(line)
        bbox.getSize(ssize)
        const fence = line.children[0];
        if (fence) {
            const box = new Box3();
            fence.children.forEach(element => {
                box.expandByObject(element);
            });
            box.getSize(size.value)
        }
    }
    console.log(`${props.number} ${JSON.stringify(size.value)}  ${JSON.stringify(ssize)}`)
    switch (props.number) {
        case 1: break;
        case 2:
            // position.value.x = size.value.z * props.count
            // position.value.z = size.value.z * props.count
            position.value.x = ssize.z * -1
            position.value.z = ssize.z
            break;
        case 3:
            // position.value.x = size.value.x * props.count * 3
            // position.value.z = size.value.x * props.count * 1 * -1
            position.value.x = ssize.x
            position.value.z = ssize.x * -1
            break;
        case 4:
            // position.value.x = size.value.y * props.count * 0.25 * -1
            // position.value.z = size.value.y * props.count * 3 * -1
            position.value.x = ssize.y
            position.value.z = ssize.y * -1
            break;
    }
}
onMounted(() => {
    count_pos()
})
watch(() => [props.count, section_count.value, extra_section.value], count_pos)
</script>
<template>
    <TresGroup :name="`line_${props.number}`" :rotate-y="rotate()" :position-z="position.z" :position-x="position.x">
        <template v-for="i in props.count">
            <template v-if="(i + (props.number - 1) * props.count) <= total"
                :key="(i + (props.number - 1) * props.count)">
                <ModelFence :index="i + (props.number - 1) * props.count" :models="props.models" />
            </template>
        </template>
    </TresGroup>
</template>