import * as THREE from 'three';

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

function handleMeshDown(
    event: Types.MeshEvent,
    currentWallItem: Types.RefMesh,
    setSelectedWallItem: Types.setSelectedWallItemSetState,
    setSelectedItemsIndex: Types.setSelectedItemsIndexSetState,
    wallItems: Types.wallItems,
    toggleView: Types.Boolean
): void {

    //////////  To select which of the Wall item and CSG is selected to be dragged  //////////

    if (!toggleView) {
        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);
        }

        if (event.intersections.length > 0) {
            const clickedIndex = wallItems.findIndex((item) => item.model === event.intersections[0]?.object?.parent?.parent);
            if (clickedIndex !== -1) {
                setSelectedItemsIndex(clickedIndex);
                const wallItemModel = wallItems[clickedIndex]?.model;
                if (wallItemModel && wallItemModel.parent && wallItemModel.parent.parent) {
                    currentWallItem.current = (wallItemModel.parent.parent.children[0]?.children[1]?.children[0] as Types.Mesh) || null;
                    setSelectedWallItem(wallItemModel.parent);
                    // 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("green");
                    //                 }
                    //             });
                    //         } else if (material instanceof THREE.MeshStandardMaterial) {
                    //             material.emissive = new THREE.Color("green");
                    //         }
                    //     }
                    // });
                }
            }
        }
    }
}
export default handleMeshDown;
