<svelte:head>
    <title>{`${ $current ? `${$current.title} ∴ ` : ''}Eldritch Radio`}</title>
</svelte:head>

<div class="app container">
    <Header></Header>

    <section class="viewer">
        {#if $current}
            <Viewer></Viewer>
            <Controls></Controls>
        {/if}
    </section>

    <section class="queue">
        <Queue></Queue>
    </section>

    <Footer></Footer>
</div>

<script>
    import { onMount, onDestroy } from 'svelte'
    import { get } from 'svelte/store'

    import Header from '/components/layout/Header.svelte'
    import Footer from '/components/layout/Footer.svelte'
    import Controls from '/components/Controls.svelte'
    import Queue from '/components/Queue.svelte'
    import Viewer from '/components/Viewer.svelte'
    import { hashtagsIterator } from '/services/mastodon.js'
    import { tracksIterator } from '/services/misc.js'

    import { domain, hashtags, queue, next, current, enqueueing, select } from '/store.js'

    let nextUnsubcribe = null
    let currentUnsubcribe = null

    onMount(async () => {
        const domainValue = get(domain)
        const hashtagsValue = get(hashtags)

        const iterator = tracksIterator(hashtagsIterator(domainValue, hashtagsValue))

        const { value: first } = await iterator.next()

        queue.set([first])
        select(first)

        nextUnsubcribe = next.subscribe(async nextValue => {
            if (nextValue === null) {
                if (!get(enqueueing)) {
                    enqueueing.set(true)

                    const { value: newTrack } = await iterator.next()

                    if (newTrack) {
                        queue.update(queueValue => [...queueValue, newTrack])
                        next.set(newTrack)
                    }

                    enqueueing.set(false)
                }
            }
        })

        currentUnsubcribe = current.subscribe(currentValue => {
            if (currentValue !== null) {
                next.update(nextValue => {
                    if (nextValue === currentValue) {
                        return null
                    } else {
                        return nextValue
                    }
                })
            }
        })
    })

    onDestroy(() => {
        for (const unsubcribe of [nextUnsubcribe, currentUnsubcribe]) {
            if (unsubcribe) {
                unsubcribe()
            }
        }
    })
</script>