import { Socket } from "socket.io-client";
import * as THREE from "three";
import { getUserData } from "../../../../functions/getUserData";
import { CameraControls } from "@react-three/drei";
import { setCameraApi } from "../../../../services/factoryBuilder/camera/setCameraApi";

export default function updateCamPosition(
    controls: React.RefObject<CameraControls>,
    socket: Socket,
    position: THREE.Vector3,
    rotation: THREE.Euler,
    projectId?: string
) {
    const { userId, organization } = getUserData();
    if (!controls.current || !projectId) return;
    const target = controls.current.getTarget(new THREE.Vector3());

    if (!socket?.connected) {
        // API

        setCameraApi(
            projectId,
            position,
            new THREE.Vector3(target.x, 0, target.z),
            new THREE.Vector3(rotation.x, rotation.y, rotation.z),
        )
    } else {
        // SOCKET

        const camData = {
            organization,
            userId: userId,
            position: position,
            target: new THREE.Vector3(target.x, 0, target.z),
            rotation: new THREE.Vector3(rotation.x, rotation.y, rotation.z),
            socketId: socket.id,
            projectId,
        };
        socket.emit("v1:Camera:set", camData);
    }
}
