<script setup lang="ts">
import { ReinhardToneMapping, PCFShadowMap, RepeatWrapping } from 'three';
import { useTexture } from '@tresjs/core'
import { useGLTF } from '@tresjs/cientos'
const section_count = useState('section_count')

const { scene, renderer, camera } = useTresContext()
renderer.value.toneMapping = ReinhardToneMapping

renderer.value.shadowMap.enabled = true
renderer.value.shadowMap.type = PCFShadowMap

const pbrTexture = await useTexture({
    map: '/texture/Ground039_4K-JPG_Color.jpg',
    displacementMap: '/texture/Ground039_4K-JPG_Displacement.jpg',
    roughnessMap: '/texture/Ground039_4K-JPG_Roughness.jpg',
    normalMap: '/texture/Ground039_4K-JPG_NormalGL.jpg',
    aoMap: '/texture/Ground039_4K-JPG_AmbientOcclusion.jpg',
    metalnessMap: '/texture/Ground039_4K-JPG_Color.jpg',
    // matcap: '/textures/Ground039_4K-JPG_Color.jpg',
    // alphaMap: '/textures/myAlphaMapTexture.jpg'
})
const repeat = 5
for (const key in pbrTexture) {
    if (Object.prototype.hasOwnProperty.call(pbrTexture, key)) {
        const element = pbrTexture[key];
        if (element && element.wrapS) {
            element.wrapS = RepeatWrapping
            element.wrapT = RepeatWrapping
            element.repeat.x = repeat
            element.repeat.y = repeat
        }
    }
}
const { scene: top } = await useGLTF('/models_one/verh_100.glb')
const { scene: fence } = await useGLTF('/models_one/fence.glb')
const { scene: fastening } = await useGLTF('/models_one/krepleniye_planok (1).glb')
const { scene: lamelle } = await useGLTF('/models_one/lamel_100.glb')

const { seek, seekAll } = useSeek()
watch(section_count, () => {
    const fences = seekAll(scene.value, 'name', 'fence')
    const base = seek(scene.value, 'name', 'base')
    const n = (section_count.value as number)
    if (fences.length > n) {
        for (let i = fences.length; i > n; i--) {
            const item = fences[i - 1]
            if (item) {
                base?.remove(item)
            }
        }
    }
})
</script>
<template>
    <TresGroup :translate-y="-3.25" name="base">
        <TresMesh receive-shadow :translate-y="-0.5" name="ground">
            <TresCircleGeometry :args="[55, 32]" :rotate-x="-Math.PI * 0.5" />
            <TresMeshStandardMaterial v-bind="pbrTexture" :metalness="1" :roughness="0.8" :opacity="0.5" />
        </TresMesh>
        <template v-for="i in section_count">
            <template v-if="i <= 20">
                <ModelFence :index="i" :models="{ top, fence, fastening, lamelle }" />
            </template>
        </template>
    </TresGroup>
</template>