const videoElement = document.getElementById('video');
let localConnection;
let wsConnection;
let mediaConstraints = { video: true, audio: true };
let iceCandidates = [];

const wsUrl = "ws://localhost:8080/api/v1/preview/5a59a94f-264a-4d24-9e57-8a9be0ecbdbd/KALANI-3.LOCAL%20%28OBS%29";  // Replace with your WebSocket URL
const peerConnectionConfig = {
    iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
};

// Initialize WebSocket connection
function initWebSocket() {
    wsConnection = new WebSocket(wsUrl);

    wsConnection.onopen = () => {
        console.log('Connected to WebSocket');
        createOffer();
    };

    wsConnection.onmessage = async (message) => {
        const signal = JSON.parse(message.data);

        if (signal.type === 'offer') {
            handleOffer(signal);
        } else if (signal.type === 'answer') {
            handleAnswer(signal);
        } else if (signal.type === 'ice') {
            handleIceCandidate(signal);
        }
    };
}

// Create an SDP offer
async function createOffer() {
    localConnection = new RTCPeerConnection(peerConnectionConfig);
    localConnection.onicecandidate = handleIceCandidateEvent;
    localConnection.ontrack = (event) => {
        videoElement.srcObject = event.streams[0];
    };

    const stream = await navigator.mediaDevices.getUserMedia(mediaConstraints);
    stream.getTracks().forEach(track => localConnection.addTrack(track, stream));

    const offer = await localConnection.createOffer();
    await localConnection.setLocalDescription(offer);

    const signalMessage = {
        type: 'offer',
        sdp: offer.sdp
    };

    wsConnection.send(JSON.stringify(signalMessage));
}

// Handle SDP offer from the server
function handleOffer(signal) {
    const remoteDescription = new RTCSessionDescription({
        type: 'offer',
        sdp: signal.sdp
    });

    localConnection.setRemoteDescription(remoteDescription)
        .then(() => {
            return localConnection.createAnswer();
        })
        .then((answer) => {
            return localConnection.setLocalDescription(answer);
        })
        .then(() => {
            const answerMessage = {
                type: 'answer',
                sdp: localConnection.localDescription.sdp
            };
            wsConnection.send(JSON.stringify(answerMessage));
        })
        .catch(console.error);
}

// Handle SDP answer from the server
function handleAnswer(signal) {
    const remoteDescription = new RTCSessionDescription({
        type: 'answer',
        sdp: signal.sdp
    });

    localConnection.setRemoteDescription(remoteDescription).catch(console.error);
}

// Handle ICE candidates
function handleIceCandidateEvent(event) {
    if (event.candidate) {
        const iceMessage = {
            type: 'ice',
            ice: {
                candidate: event.candidate.candidate,
                sdpMid: event.candidate.sdpMid,
                sdpMLineIndex: event.candidate.sdpMLineIndex
            }
        };
        wsConnection.send(JSON.stringify(iceMessage));
    }
}

// Handle ICE candidate from the server
function handleIceCandidate(signal) {
    const candidate = new RTCIceCandidate({
        candidate: signal.ice.candidate,
        sdpMid: signal.ice.sdpMid,
        sdpMLineIndex: signal.ice.sdpMLineIndex
    });

    localConnection.addIceCandidate(candidate).catch(console.error);
}

// Initialize the connection
initWebSocket();