import * as THREE from 'three';

import * as Types from "../../../../types/world/worldTypes";

function hideRoof(
    visibility: Types.Boolean,
    floorGroup: Types.RefGroup,
    camera: THREE.Camera
): void {

    //////////  Toggles the visibility of the roof based on the camera position and the Roof visibility button on UI  //////////

    const v = new THREE.Vector3();
    const u = new THREE.Vector3();

    if (visibility === true && floorGroup.current) {
        for (const child of floorGroup.current.children) {
            if (child.name.includes("Roof")) {
                const roofChild = child as Types.Mesh;
                roofChild.getWorldDirection(v);
                camera?.getWorldDirection(u);
                if (roofChild.material) {
                    const materials = Array.isArray(roofChild.material) ? roofChild.material : [roofChild.material];
                    materials.forEach(material => {
                        material.visible = v.dot(u) < 0.25;
                    });
                }
            }
        }
    } else {
        if (floorGroup.current) {
            for (const child of floorGroup.current.children) {
                if (child.name.includes("Roof")) {
                    const roofChild = child as Types.Mesh;
                    if (roofChild.material) {
                        const materials = Array.isArray(roofChild.material) ? roofChild.material : [roofChild.material];
                        materials.forEach(material => {
                            material.visible = false;
                        });
                    }
                }
            }
        }
    }
}

export default hideRoof;
