import { toast } from 'react-toastify';
import RemoveConnectedLines from '../lines/removeConnectedLines';

import * as Types from '../../../../types/world/worldTypes';
import { Socket } from 'socket.io-client';
// import { deleteLayer } from '../../../../services/factoryBuilder/lines/deleteLayerApi';

async function DeleteLayer(
    removedLayer: Types.Number,
    lines: Types.RefLines,
    floorPlanGroupLine: Types.RefGroup,
    floorPlanGroupPoint: Types.RefGroup,
    onlyFloorlines: Types.RefOnlyFloorLines,
    floorGroup: Types.RefGroup,
    setDeletedLines: any,
    setRemovedLayer: Types.setRemoveLayerSetState,
    socket: Socket<any>
): Promise<void> {

    //////////  Remove the Lines from the lines.current based on the removed layer and rearrange the layer number that are higher than the removed layer  //////////

    const removedLines: Types.Lines = lines.current.filter(line => line[0][2] === removedLayer);

    const email = localStorage.getItem('email')
    const organization = (email!.split("@")[1]).split(".")[0];

    //REST

    // await deleteLayer(organization, removedLayer);

    //SOCKET

    const data = {
        organization: organization,
        layer: removedLayer,
        socketId: socket.id
    }

    socket.emit('v1:Line:delete:layer', data);

    //////////  Remove Points and lines from the removed layer  //////////

    removedLines.forEach((line) => {
        line.forEach((removedPoint) => {
            RemoveConnectedLines(removedPoint[1], floorPlanGroupLine, floorPlanGroupPoint, setDeletedLines, lines);
        });
    });

    //////////  Update the remaining lines layer values in the userData and in lines.current  ////////// 

    let remaining = lines.current.filter(line => line[0][2] !== removedLayer);
    let updatedLines: Types.Lines = [];
    remaining.forEach(line => {
        let newLines: Types.Line = [...line];
        if (newLines[0][2] > removedLayer) {
            newLines[0][2] -= 1;
            newLines[1][2] -= 1;
        }

        const matchingLine = floorPlanGroupLine.current.children.find(l => l.userData.linePoints[0][1] === line[0][1] && l.userData.linePoints[1][1] === line[1][1]);
        if (matchingLine) {
            const updatedUserData = matchingLine.userData;
            updatedUserData.linePoints[0][2] = newLines[0][2];
            updatedUserData.linePoints[1][2] = newLines[1][2];
        }
        updatedLines.push(newLines);
    });

    lines.current = updatedLines;
    localStorage.setItem("Lines", JSON.stringify(lines.current));

    //////////  Also remove OnlyFloorLines and update it in localstorage  //////////

    onlyFloorlines.current = onlyFloorlines.current.filter((floor) => {
        return floor[0][0][2] !== removedLayer;
    });
    const meshToRemove: any = floorGroup.current?.children.find((mesh) =>
        mesh.name === `Only_Floor_Line_${removedLayer}`
    );
    if (meshToRemove) {
        (<any>meshToRemove.material).dispose();
        (<any>meshToRemove.geometry).dispose();
        floorGroup.current?.remove(meshToRemove);
    }

    toast.success("Layer Removed!");
    setRemovedLayer(null);
}
export default DeleteLayer;
