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

function hideWalls(
    visibility: Types.Boolean,
    scene: THREE.Scene,
    camera: THREE.Camera
): void {
    const wallNormal = new THREE.Vector3();
    const cameraToWall = new THREE.Vector3();
    const cameraDirection = new THREE.Vector3();

    if (visibility === true) {
        for (const children of scene.children) {
            if (children.name === "Walls" && children.children[0]?.children.length > 0) {
                children.children[0].children.forEach((child: any) => {
                    if (child.children[0]?.userData.WallType === "RoomWall") {
                        const wallMesh = child.children[0];
                        wallMesh.getWorldDirection(wallNormal);
                        cameraToWall.copy(wallMesh.position).sub(camera.position).normalize();
                        camera.getWorldDirection(cameraDirection);
                        const isFacingCamera = wallNormal.dot(cameraToWall) > 0;
                        const isInFrontOfCamera = cameraDirection.dot(cameraToWall) > -0.3;

                        if (wallMesh.material) {
                            wallMesh.material.visible = isFacingCamera && isInFrontOfCamera;
                        }
                    }
                });
            }
        }
    } else {
        for (const children of scene.children) {
            if (children.name === "Walls" && children.children[0]?.children.length > 0) {
                children.children[0].children.forEach((child: any) => {
                    if (child.children[0]?.userData.WallType === "RoomWall" && child.children[0].material) {
                        child.children[0].material.visible = true;
                    }
                });
            }
        }
    }
}

export default hideWalls;