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

function handleMeshMissed(
    currentWallItem: Types.RefMesh,
    setSelectedWallItem: Types.setSelectedWallItemSetState,
    setSelectedItemsIndex: Types.setSelectedItemsIndexSetState
): void {

    //////////  If an item is selected and then clicked outside other than the selected object, this runs and removes the color of the selected object and sets setSelectedWallItem and setSelectedItemsIndex as null  //////////

    if (currentWallItem.current) {
        currentWallItem.current.children.forEach((child) => {
            if ((child as THREE.Mesh).isMesh && child.name !== "CSG_REF") {
                const material = (child as THREE.Mesh).material;

                if (Array.isArray(material)) {
                    material.forEach(mat => {
                        if (mat instanceof THREE.MeshStandardMaterial) {
                            mat.emissive = new THREE.Color("black");
                        }
                    });
                } else if (material instanceof THREE.MeshStandardMaterial) {
                    material.emissive = new THREE.Color("black");
                }
            }
        });
        currentWallItem.current = null;
        setSelectedWallItem(null);
        setSelectedItemsIndex(null);
    }
}

export default handleMeshMissed;
