import { Geometry } from "@react-three/csg";
import {
    useSelectedWallItem,
    useToggleView,
    useToolMode,
    useWallItems,
    useWalls,
} from "../../../store/builder/store";
import handleMeshDown from "../eventFunctions/handleMeshDown";
import handleMeshMissed from "../eventFunctions/handleMeshMissed";
import WallsMesh from "./wallsMesh";
import WallItemsGroup from "./wallItemsGroup";

const WallsAndWallItems = ({
    CSGGroup,
    setSelectedItemsIndex,
    selectedItemsIndex,
    currentWallItem,
    csg,
    lines,
    hoveredDeletableWallItem,
}: any) => {
    const { walls } = useWalls();
    const { wallItems } = useWallItems();
    const { toggleView } = useToggleView();
    const { toolMode } = useToolMode();
    const { setSelectedWallItem } = useSelectedWallItem();

    return (
        <mesh
            ref={CSGGroup as any}
            name="Walls"
            key={walls.length}
            receiveShadow
            visible={!toggleView}
            onClick={(event) => {
                if (toolMode === "cursor") {
                    handleMeshDown(
                        event,
                        currentWallItem,
                        setSelectedWallItem,
                        setSelectedItemsIndex,
                        wallItems,
                        toggleView
                    );
                }
            }}
            onPointerMissed={() => {
                if (toolMode === "cursor") {
                    handleMeshMissed(
                        currentWallItem,
                        setSelectedWallItem,
                        setSelectedItemsIndex
                    );
                    setSelectedWallItem(null);
                    setSelectedItemsIndex(null);
                }
            }}
        >
            <Geometry ref={csg as any} computeVertexNormals useGroups>
                <WallsMesh lines={lines} />
                <WallItemsGroup
                    currentWallItem={currentWallItem}
                    hoveredDeletableWallItem={hoveredDeletableWallItem}
                    selectedItemsIndex={selectedItemsIndex}
                    setSelectedItemsIndex={setSelectedItemsIndex}
                    CSGGroup={CSGGroup}
                />
            </Geometry>
        </mesh>
    );
};

export default WallsAndWallItems;
