import * as THREE from 'three';

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

function RemoveConnectedLines(
    DeletedPointUUID: Types.String,
    floorPlanGroupLine: Types.RefGroup,
    floorPlanGroupPoint: Types.RefGroup,
    setDeletedLines: any,
    lines: Types.RefLines,
): void {

    //////////  Check if any and how many lines are connected to the deleted point  //////////

    const removableLines: THREE.Mesh[] = [];
    const connectedpoints: string[] = [];

    const removedLinePoints: [number, string, number][][] = []; // Array to hold linePoints of removed lines

    floorPlanGroupLine.current.children.forEach((line) => {
        const linePoints = line.userData.linePoints as [number, string, number][];
        const uuid1 = linePoints[0][1];
        const uuid2 = linePoints[1][1];

        if (uuid1 === DeletedPointUUID || uuid2 === DeletedPointUUID) {
            connectedpoints.push(uuid1 === DeletedPointUUID ? uuid2 : uuid1);
            removableLines.push(line as THREE.Mesh);
            removedLinePoints.push(linePoints);
        }
    });

    if (removableLines.length > 0) {
        removableLines.forEach((line) => {
            lines.current = lines.current.filter(item => item !== line.userData.linePoints);
            (<any>line.material).dispose();
            (<any>line.geometry).dispose();
            floorPlanGroupLine.current.remove(line);
        });
    }
    setDeletedLines(removedLinePoints)

    //////////  Check and Remove point that are no longer connected to any lines  //////////

    connectedpoints.forEach((pointUUID) => {
        let isConnected = false;
        floorPlanGroupLine.current.children.forEach((line) => {
            const linePoints = line.userData.linePoints as [number, string, number][];
            const uuid1 = linePoints[0][1];
            const uuid2 = linePoints[1][1];
            if (uuid1 === pointUUID || uuid2 === pointUUID) {
                isConnected = true;
            }
        });
        if (!isConnected) {
            floorPlanGroupPoint.current.children.forEach((point: any) => {
                if (point.uuid === pointUUID) {
                    (<any>point.material).dispose();
                    (<any>point.geometry).dispose();
                    floorPlanGroupPoint.current.remove(point);
                }
            });
        }
    });
}

export default RemoveConnectedLines;
