<script setup lang="ts">
import {
    ReinhardToneMapping, PCFSoftShadowMap,
    PMREMGenerator, Euler,
} from 'three';
import { EXRLoader } from 'three/examples/jsm/Addons.js';
import { useGLTF, } from '@tresjs/cientos'

const section_count = useState<number>('section_count')
const extra_section = use_extra_section()
const max_size = use_max_size()

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

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

const { scene: top } = await useGLTF('/models_one/verh_100.glb', { draco: true })
const { scene: fence } = await useGLTF('/models_one/fence.glb', { draco: true })
const { scene: fastening } = await useGLTF('/models_one/krepleniye_planok (1).glb', { draco: true })
const { scene: lamelle } = await useGLTF('/models_one/lamel_100.glb', { draco: true })

const { seek } = useSeek()
watch([section_count, extra_section], () => {
    const base = seek(scene.value, 'name', 'base')
    const n = (section_count.value as number) + ~~(!!extra_section.value)
    if (base?.children && n < base?.children.length) {
        base.children = [...base?.children.slice(0, n)]
    }
})

const pmremGenerator = new PMREMGenerator(renderer.value);
pmremGenerator.compileEquirectangularShader();
onMounted(() => {
    new EXRLoader()
        .load('/hdrmaps/kloppenheim_06_4k.exr', function (texture) {
            const exrCubeRenderTarget = pmremGenerator.fromEquirectangular(texture);
            const exrBackground = exrCubeRenderTarget.texture;
            const newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null;

            scene.value.environment = newEnvMap
            scene.value.background = exrBackground
            scene.value.backgroundRotation = new Euler(0, 5, 0)
            texture.dispose();
        });
})

</script>
<template>
    <TresGroup name="base">
        <template v-for="i in (section_count + ~~(!!extra_section))">
            <template v-if="i <= max_size">
                <ModelFence :index="i" :models="{ top, fence, fastening, lamelle }" />
            </template>
        </template>
    </TresGroup>
</template>