<script setup lang="ts">
import {
    PCFSoftShadowMap,
    EquirectangularReflectionMapping,
    CineonToneMapping,
    Euler,
    Mesh,
    Group,
    Object3D,
} from 'three';
import { GainMapLoader, } from '@monogrid/gainmap-js'
//@ts-ignore
import { useGLTF, } from '@tresjs/cientos'
import { getColorHexFromRal, type ralTypes } from '../ral';

const pillar_color = use_pillar_color()
const lamelle_color = use_lamelle_color()
const section_count = use_section_count()
const lamelle_count = use_lamelles_count()
const extra_section = use_extra_section()
const max_size = use_max_size()

const { scene, renderer, camera } = useTresContext()
renderer.value.toneMapping = CineonToneMapping
renderer.value.toneMappingExposure = 0.5

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

const { scene: top_model } = await useGLTF('/models_one/verh_100.glb', { draco: true })
// const { scene: fence_model } = await useGLTF('/models_one/fence.glb', { draco: true })
const { scene: model_fence_top } = await useGLTF('/fence_one/top.glb')
const { scene: model_fence_center } = await useGLTF('/fence_one/center.glb')
const { scene: model_fence_bottom } = await useGLTF('/fence_one/bottom.glb')
const { scene: fastening_model } = await useGLTF('/models_one/krepleniye_planok (1).glb', { draco: true });
const { scene: lamelle_model } = await useGLTF('/models_one/lamel_100.glb', { draco: true });

[model_fence_top, model_fence_bottom].map((sc: Object3D) =>
    sc.traverse((child: Object3D) => {
        if (child instanceof Mesh) {
            child.position.z = 0
        }
    })
)

const top = ref(top_model)
const fence = ref(model_fence_center)
const fence_top = ref(model_fence_top)
const fence_bottom = ref(model_fence_bottom)
const fastening = ref(fastening_model)
const lamelle = ref(lamelle_model)

if (!pillar_color.value) {
    const r = Math.floor(Math.random() * predefPillarColors.length)
    pillar_color.value = predefPillarColors[r] as ralTypes
    lamelle_color.value = predefLamelleColors[r] as ralTypes
}

set_material(lamelle.value, getColorHexFromRal(lamelle_color.value));
[top, fastening].map((el: any) => { set_material(el.value, getColorHexFromRal(pillar_color.value)) });
[fence, fence_bottom, fence_top].map((el: any) => { set_material(el.value, getColorHexFromRal(pillar_color.value), lamelle_count.value) });

const { seek, seekAll } = useSeek()
watch(lamelle_color, () => {
    set_material(lamelle.value, getColorHexFromRal(lamelle_color.value))
    const items = seekAll(scene.value, 'name', "lamelles")
    items.forEach(element => {
        set_material(element, getColorHexFromRal(lamelle_color.value))
    });
})
watch(pillar_color, () => {
    [top, fence, fastening].map((el: any) => { set_material(el.value, getColorHexFromRal(pillar_color.value)) })
    const items = [
        ...seekAll(scene.value, 'name', "pillar_one"),
        ...seekAll(scene.value, 'name', "pillar_two"),
        ...seekAll(scene.value, 'name', "lam_fastening_one"),
        ...seekAll(scene.value, 'name', "lam_fastening_two"),
        ...seekAll(scene.value, 'name', "top_section"),
    ]
    items.forEach(element => {
        set_material(element, getColorHexFromRal(pillar_color.value))
    })
})
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)]
    }
})

watch(lamelle_count, () => {
    [fence, fence_bottom, fence_top].map((el: any) => { set_material(el.value, getColorHexFromRal(pillar_color.value), lamelle_count.value) });
})

onMounted(async () => {
    const loader = new GainMapLoader(renderer.value)
    const result = await loader.loadAsync([
        'hdrmaps/hdr.webp',
        'hdrmaps/hdr-gainmap.webp',
        'hdrmaps/hdr.json',
    ])
    if (camera.value) {
        renderer.value.render(scene.value, camera.value)
    }
    scene.value.environment = result.renderTarget.texture
    scene.value.background = result.renderTarget.texture
    scene.value.background.mapping = EquirectangularReflectionMapping
    scene.value.backgroundRotation = new Euler(0, 10, 0)
    scene.value.backgroundIntensity = 1.5
    scene.value.backgroundBlurriness = 0.06
    result.renderTarget.texture.dispose();
})

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