<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(180)
        case 3:
            return degToRad(270)
        case 4:
            return degToRad(90)
    }
}
const { seekByName } = useSeek()
const { scene } = useTresContext()

const section_count = use_section_count()
const extra_section = use_extra_section()
const fence_section = use_fence_section()
const max_size = use_max_size()

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

    const line = seekByName(scene.value, `line_${props.number}`)
    const line_size = new Vector3()
    const line_pos = new Vector3()

    if (line && line.children.length) {
        line.updateMatrixWorld()
        new Box3().expandByObject(line).getSize(line_size)
        line.getWorldPosition(line_pos)
    }
    const line1 = seekByName(scene.value, `line_1`);
    const line1_size = new Vector3()
    const line1_pos = new Vector3()
    if (line1) {
        new Box3().expandByObject(line1).getSize(line1_size)
        line1.getWorldPosition(line1_pos)
    }
    const k = ((line1_size.x / props.count) - line1_size.z) * 0.5
    switch (props.number) {
        case 1: break;
        case 2:
            position.value.z = line1_size.x * -1
            position.value.x = line1_size.x - k * 2
            break;
        case 3:
            position.value.z = line1_size.x * -1 + k
            position.value.x = -1 * k
            break;
        case 4:
            position.value.z = -1 * k
            position.value.x = line1_size.x - k
            break;
    }
}
onMounted(() => {
    count_pos()
})
watch(() => [props.count, fence_section.value, section_count.value, extra_section.value], count_pos)
</script>
<template>
    <TresGroup :name="`line_${props.number}`" :rotate-y="rotate()" :position-x="position.x" :position-y="position.y"
        :position-z="position.z">
        <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" :models="props.models"
                    :last_element="(i + (props.number - 1) * props.count) == total"
                    :first_element="i == 1 && props.count == 1" />
            </template>
        </template>
    </TresGroup>
</template>