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

import { toast } from 'react-toastify';

function deleteLine(
    hoveredDeletableLine: Types.RefMesh,
    onlyFloorlines: Types.RefOnlyFloorLines,
    lines: Types.RefLines,
    floorPlanGroupLine: Types.RefGroup,
    floorPlanGroupPoint: Types.RefGroup,
    setDeletedLines: any,
    socket: Socket<any>
): void {

    //////////  Deleting a line and the points if they are not connected to any other line  //////////

    if (!hoveredDeletableLine.current) {
        return;
    }

    const linePoints = hoveredDeletableLine.current.userData.linePoints;
    const connectedpoints = [linePoints[0][1], linePoints[1][1]];

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

    //REST

    // deleteLineApi(
    //     organization,
    //     [
    //         { "uuid": linePoints[0][1] },
    //         { "uuid": linePoints[1][1] }
    //     ]
    // )

    //SOCKET

    const data = {
        organization: organization,
        line: [
            { "uuid": linePoints[0][1] },
            { "uuid": linePoints[1][1] }
        ],
        socketId: socket.id
    }

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


    onlyFloorlines.current = onlyFloorlines.current.map(floorline =>
        floorline.filter(line => line[0][1] !== connectedpoints[0] && line[1][1] !== connectedpoints[1])
    ).filter(floorline => floorline.length > 0);

    lines.current = lines.current.filter(item => item !== linePoints);
    (<any>hoveredDeletableLine.current.material).dispose();
    (<any>hoveredDeletableLine.current.geometry).dispose();
    floorPlanGroupLine.current.remove(hoveredDeletableLine.current);
    setDeletedLines([linePoints]);

    connectedpoints.forEach((pointUUID) => {
        let isConnected = false;
        floorPlanGroupLine.current.children.forEach((line) => {
            const linePoints = line.userData.linePoints;
            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);
                }
            });
        }
    });

    toast.success("Line Removed!");
}

export default deleteLine;
