<script lang="ts">
    import { onMount } from "svelte";

    let localVideo: HTMLVideoElement;
    let pc: RTCPeerConnection;
    let ws: WebSocket;

    async function start() {
        pc = new RTCPeerConnection({
            iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
        });

        ws = new WebSocket("wss://meet-api.quizer.space/ws");

        ws.onmessage = async (e) => {
            const msg = JSON.parse(e.data);

            if (msg.type === "answer") {
                await pc.setRemoteDescription(msg.data);
            }

            if (msg.type === "ice") {
                await pc.addIceCandidate(msg.data);
            }

            if (msg.type === "renegotiate") {
                const offer = await pc.createOffer();
                await pc.setLocalDescription(offer);

                ws.send(
                    JSON.stringify({
                        type: "offer",
                        data: offer,
                    }),
                );
            }
        };

        pc.onicecandidate = (e) => {
            if (e.candidate) {
                ws.send(
                    JSON.stringify({
                        type: "ice",
                        data: e.candidate,
                    }),
                );
            }
        };

        pc.ontrack = (e) => {
            const video = document.createElement("video");
            video.autoplay = true;
            video.srcObject = e.streams[0];
            document.body.appendChild(video);
        };

        const stream = await navigator.mediaDevices.getUserMedia({
            video: true,
            audio: true,
        });

        localVideo.srcObject = stream;

        for (const track of stream.getTracks()) {
            pc.addTrack(track, stream);
        }

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

        ws.onopen = () => {
            ws.send(
                JSON.stringify({
                    type: "offer",
                    data: offer,
                }),
            );
        };
    }

    onMount(() => {
        start();
    });
</script>

<video bind:this={localVideo} autoplay muted playsinline></video>
