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) {
            if (event.object) {
                const wallItemModel = event.object;
                let currentObject = wallItemModel as THREE.Object3D;
                while (currentObject) {
                    if (currentObject.name === "Scene") {
                        break;
                    }
                    currentObject = currentObject.parent as THREE.Object3D;
                }
                if (!currentObject) return;
                const clickedIndex = wallItems.findIndex((item) => item.model?.uuid === currentObject.uuid);
                if (clickedIndex !== -1) {
                    setSelectedItemsIndex(clickedIndex);
                    const wallItemModel = wallItems[clickedIndex]?.model;
                    if (wallItemModel) {
                        setSelectedWallItem(wallItemModel);
                    }
                }
            }

        }
    }
}
export default handleMeshDown;
