<script>
 import { goto, invalidate } from '$app/navigation';

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

 import { getExerciceQA, QAComment } from '$lib/qa.js';
 import BadgeState from '$lib/components/BadgeState.svelte';

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

 export let theme = null;
 export let exercice = { };
 export let query_selected = null;
 export let queries = [];

 let thumbInProgress = null;
 function thumbUp(qid) {
     thumbInProgress = qid;
     const thumb = new QAComment({
         content: "+1",
     });
     thumb.save(qid).then(() => {
         thumbInProgress = null;
         invalidate(`api/exercices/${exercice.id}/qa`);
     })
 }
</script>

<div class="list-group {className}" class:list-group-flush={true}>
    {#if queries.length}
        {#each queries as q (q.id)}
            <button
                type="button"
                class="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
                class:active={query_selected && q.id == query_selected}
                aria-current="true"
                on:click={() => goto(theme?`themes/${theme.id}/${exercice.id}/${q.id}`:`exercices/${exercice.id}/${q.id}`)}
            >
                <div class="text-truncate">
                    <BadgeState state={q.state} />
                    {#if !q.solved}
                        <strong>{q.subject}</strong>
                    {:else if !q.closed}
                        {q.subject}
                    {:else}
                        <s>{q.subject}</s>
                    {/if}
                </div>
                {#if !q.closed}
                    <button
                        type="button"
                        class="btn btn-sm btn-info"
                        disabled={thumbInProgress !== null}
                              on:click|preventDefault={() => thumbUp(q.id)}
                    >
                        {#if thumbInProgress == q.id}
                            <Spinner size="sm" />
                        {:else}
                            <Icon name="hand-thumbs-up-fill" />
                        {/if}
                    </button>
                {/if}
            </button>
        {/each}
    {:else}
        <div class="fw-bold text-center">
            Aucune requête enregistrée
        </div>
    {/if}
</div>
