import * as THREE from 'three';
import { DragControls } from 'three/examples/jsm/controls/DragControls';
import * as CONSTANTS from '../../../types/world/worldConstants';
import DragPoint from '../geomentries/points/dragPoint';

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

export default async function addDragControl(
    dragPointControls: Types.RefDragControl,
    currentLayerPoint: Types.RefMeshArray,
    state: Types.ThreeState,
    floorPlanGroupPoint: Types.RefGroup,
    floorPlanGroupLine: Types.RefGroup,
    lines: Types.RefLines,
    onlyFloorlines: Types.RefOnlyFloorLines,
    socket: Socket<any>
) {

    //////////  Dragging Point and also change the size to indicate during hover  //////////

    dragPointControls.current = new DragControls(currentLayerPoint.current, state.camera, state.gl.domElement);
    dragPointControls.current.enabled = false;

    dragPointControls.current.addEventListener('drag', function (event) {
        const object = event.object;
        if (object.visible) {
            (state.controls as any).enabled = false;
            DragPoint(event as any, floorPlanGroupPoint, floorPlanGroupLine, state.scene, lines, onlyFloorlines)
        } else {
            (state.controls as any).enabled = true;
        }
    });

    dragPointControls.current.addEventListener('dragstart', function (event) {
    });

    dragPointControls.current.addEventListener('dragend', async function (event) {
        if (!dragPointControls.current) return;
        const email = localStorage.getItem('email')
        const organization = (email!.split("@")[1]).split(".")[0];

        //REST

        // await updatePoint(
        //     organization,
        //     { "x": event.object.position.x, "y": 0.01, "z": event.object.position.z },
        //     event.object.uuid,
        // )

        //SOCKET

        const data = {
            organization: organization,
            position: { "x": event.object.position.x, "y": 0.01, "z": event.object.position.z },
            uuid: event.object.uuid,
            socketId: socket.id
        }

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

        if (state.controls) {
            (state.controls as any).enabled = true;
        }
    });

    dragPointControls.current.addEventListener('hoveron', function (event: any) {
        if ((event.object as Types.Mesh).name === "point") {
            event.object.material.uniforms.uInnerColor.value.set(event.object.userData.color)
        }
    });

    dragPointControls.current.addEventListener('hoveroff', function (event: any) {
        if ((event.object as Types.Mesh).name === "point") {
            event.object.material.uniforms.uInnerColor.value.set(new THREE.Color(CONSTANTS.pointConfig.defaultInnerColor))
        }
    });

}