<script setup lang="ts">
import type { Object3D } from 'three';
import { getColorHexFromRal, type ralTypes } from '../ral';

const props = defineProps(['models'])

const pillar_color = use_pillar_color()
const pillar_pattern = use_pattern()
const lamelle_color = use_lamelle_color()
const lamelle_count = use_lamelles_count()
const remove_pillar = use_remove_pillar()

const { top, fence, fence_top, fence_bottom, fence_inner, fastening, lamelle } = props.models
const { scene } = useTresContext()
const { seekAll } = useSeek()

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
}

const recolorLamelles = () => {
    [
        lamelle,
        ...seekAll(scene.value, 'name', "lamelles"),
    ].map((el: Object3D) => { set_material(el, getColorHexFromRal(lamelle_color.value)) });
}

const recolorPillar = () => {
    [
        top, fastening, fence, fence_bottom, fence_top,
        ...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"),
    ].map((el: Object3D) => { set_material(el, getColorHexFromRal(pillar_color.value)) });
}

const recolorPillarPattern = () => {
    [fence_inner].map(
        (el: Object3D) => {
            set_material(el, getColorHexFromRal(pillar_color.value), {
                pattern: pillar_pattern.value,
                count: lamelle_count.value
            })
        });
}

recolorLamelles();
recolorPillar();
recolorPillarPattern();

watch(lamelle_color, recolorLamelles)
watch(pillar_color, recolorPillar)
watch([pillar_color, pillar_pattern, lamelle_count, remove_pillar], recolorPillarPattern)
</script>
<template>
</template>