// https://web.dev/articles/webrtc-basics

// handles JSON.stringify/parse

class SignalingChannel {
    send(message) {
        console.log(message);
    }
}


function createPeerConnection(targetPeer) {
    
    const signaling = new SignalingChannel();

    // const constraints = {audio: true, video: true};
    const configuration = { iceServers: [{ urls: 'stun:stunserver2024.stunprotocol.org' }] };
    const peerConnection = new RTCPeerConnection(configuration);
    const sendChannel = peerConnection.createDataChannel('default');


    // Send any ice candidates to the other peer.
    peerConnection.onicecandidate = ({ candidate }) => signaling.send({ candidate });

    // Let the "negotiationneeded" event trigger offer generation.
    peerConnection.onnegotiationneeded = async () => {
        try {
            await peerConnection.setLocalDescription(await peerConnection.createOffer());
            // Send the offer to the other peer.
            signaling.send({ desc: peerConnection.localDescription });
        } catch (err) {
            console.error(err);
        }
    };

    // // Once remote track media arrives, show it in remote video element.
    // peerConnection.ontrack = (event) => {
    //   // Don't set srcObject again if it is already set.
    //   if (remoteView.srcObject) return;
    //   remoteView.srcObject = event.streams[0];
    // };

    // Call start() to initiate.
    async function start() {
        //   try {
        // Get local stream, show it in self-view, and add it to be sent.
        //     const stream =
        //       await navigator.mediaDevices.getUserMedia(constraints);
        //     stream.getTracks().forEach((track) =>
        //       peerConnection.addTrack(track, stream));
        //     selfView.srcObject = stream;
        //   } catch (err) {
        //     console.error(err);
        //   }
    }

    signaling.onmessage = async ({ desc, candidate }) => {
        try {
            if (desc) {
                // If you get an offer, you need to reply with an answer.
                if (desc.type === 'offer') {
                    await peerConnection.setRemoteDescription(desc);
                    // const stream =
                    //     await navigator.mediaDevices.getUserMedia(constraints);
                    // stream.getTracks().forEach((track) =>
                    //     peerConnection.addTrack(track, stream));
                    await peerConnection.setLocalDescription(await peerConnection.createAnswer());
                    signaling.send({ desc: peerConnection.localDescription });
                } else if (desc.type === 'answer') {
                    await peerConnection.setRemoteDescription(desc);
                } else {
                    console.log('Unsupported SDP type.');
                }
            } else if (candidate) {
                await peerConnection.addIceCandidate(candidate);
            }
        } catch (err) {
            console.error(err);
        }
    };

}

