<script>
 import { goto } from '$app/navigation';
 import { page } from '$app/stores';

 import {
     Button,
     Icon,
     Spinner,
 } from 'sveltestrap';

 import { tracks } from '$lib/stores/tracks';

 export let flush = false;
 export let edit = false;

 export { className as class };
 let className = '';

 let refreshInProgress = false;
 function refresh_tracks() {
     refreshInProgress = true;
     tracks.refresh().then(() => {
         refreshInProgress = false;
     });
 }
</script>

<div class="d-flex justify-content-between align-items-center" class:px-2={flush}>
    <h2>
        Musiques {#if !flush}du réveil{/if}
    </h2>
    <div>
        {#if !edit}
            <Button
                href="musiks/tracks"
                color="outline-info"
                size="sm"
            >
                <Icon name="pencil" />
            </Button>
        {/if}
        <Button
            href="musiks/tracks/new"
            color="outline-primary"
            size="sm"
        >
            <Icon name="plus-lg" />
        </Button>
        <Button
            color="outline-dark"
            size="sm"
            title="Rafraîchir la liste des pistes"
            on:click={refresh_tracks}
            disabled={refreshInProgress}
        >
            {#if !refreshInProgress}
                <Icon name="arrow-clockwise" />
            {:else}
                <Spinner color="dark" size="sm" />
            {/if}
        </Button>
    </div>
</div>
<div class="list-group {className}" class:list-group-flush={flush}>
    {#if $tracks.list}
        {#each $tracks.list as track (track.id)}
            <button
                type="button"
                class="list-group-item list-group-item-action"
                class:active={$page.url.pathname.indexOf('/tracks/') !== -1 && $page.params.tid == track.id}
                aria-current="true"
                on:click={() => {
                         if (edit) {
                             goto('musiks/tracks/' + track.id);
                         } else {
                             track.toggleEnable().then((t) => {
                                 refresh_tracks();
                             })
                         }
                         }}
            >
                {#if !edit}
                    <input class="form-check-input me-1" type="checkbox" checked={track.enabled}>
                {/if}
                <span class:fw-bold={!edit && track.enabled}>{track.name}</span>
            </button>
        {/each}
    {:else}
        {#await tracks.refresh()}
            <div class="d-flex justify-content-center align-items-center gap-2">
                <Spinner color="primary" /> Chargement en cours&hellip;
            </div>
        {:then}
            test
        {/await}
    {/if}
</div>
