<script lang="ts">
    import QueueSlider from "$lib/components/QueueSlider.svelte"
    import SuggestionInput from "$lib/components/SuggestionInput.svelte"
    import Error from "$lib/components/Error.svelte"
    import { parseSong, parseSuggestion, type Suggestion, type Song } from "$lib/types.js"
    import { onMount } from "svelte"
    import SuggestionList from "$lib/components/SuggestionList.svelte"

    let { data } = $props()

    let songs = $state<Song[]>([])
    let playing = $state(0)

    let suggestions = $state<Suggestion[]>([])

    let error = $state({ code: 0, message: "" })

    onMount(async () => {
        // Join the room
        let resp = await fetch("/api/join?room=" + data.roomId)

        if (resp.status != 200) {
            error = { code: 400, message: "Failed to join the room. Maybe wrong code or location?" }
            return
        }

        // Setup websocket connection

        // Get room suggestions

        resp = await fetch("/api/room/suggestions?room=" + data.roomId)

        if (resp.status != 200) {
            error = { code: 500, message: "Failed to retrive suggestions" }
            return
        }

        let json = await resp.json()

        json["songs"].forEach(async (i: any) => {
            suggestions.push(await parseSuggestion(i))
        })

        suggestions = suggestions.sort((a, b) => {
            return a.upvote - b.upvote
        })

        // Get the room queue

        resp = await fetch("/api/queue?room=" + data.roomId)
        if (resp.status != 200) {
            error = { code: 404, message: "Room not found" }
            return
        }
        json = await resp.json()

        json["queue"].forEach(async (i: any) => {
            songs.push(await parseSong(i))
        })
        console.log(songs)
    })
</script>

<!-- Check if the room exists -->
{#if error.code != 0}
    <Error code={error.code} message={error.message} />
{:else}
    <div class="flex w-full flex-col items-center justify-center p-4 lg:p-10">
        <QueueSlider {songs} {playing} />
        <div class="w-full py-6 lg:w-[30vw]">
            <SuggestionInput roomId={data.roomId} />
        </div>
        <div class="w-full py-6 lg:w-[30vw]">
            <SuggestionList {suggestions} roomId={data.roomId} />
        </div>
    </div>
{/if}
