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

 import {
     Button,
     Container,
     Icon,
     Table,
     Spinner,
 } from '@sveltestrap/sveltestrap';

 import { fieldsExercices, getThemedExercices } from '$lib/exercices';

 export let data;
 let query = "";

 function show(id) {
     goto("themes/" + $page.params.tid + "/" + id)
 }
</script>

<Container class="mt-2 mb-5">
    <div class="d-flex align-items-end">
        <Button
            class="align-self-center"
            color="link"
            on:click={() => goto('themes/')}
        >
            <Icon name="chevron-left" />
        </Button>
        <h2>
            {data.theme.name}
        </h2>
        <small class="m-2 mb-3 text-muted text-truncate">{@html data.theme.authors}</small>
    </div>

    {#if data.theme.intro}
        <Container class="text-muted" style="overflow-y: auto; max-height: 34vh">
            {@html data.theme.intro.replace("$FILES$", "../files")}
        </Container>
    {/if}

    {#await getThemedExercices($page.params.tid)}
    {:then exercices}
        <h3 class="mt-2">
            Défis ({exercices.length})
        </h3>

        <p>
            <input type="search" class="form-control form-control-sm" placeholder="Search" bind:value={query} autofocus>
        </p>
        <Table class="table-hover table-bordered table-striped table-sm">
            <thead class="thead-dark">
                <tr>
                    {#each fieldsExercices as field}
	                <th>
	                    {field}
	                </th>
                    {/each}
                </tr>
            </thead>
            <tbody>
                {#each exercices as exercice (exercice.id)}
                    {#if exercice.title.indexOf(query) >= 0}
                        <tr on:click={() => show(exercice.id)}>
                            {#each fieldsExercices as field}
	                        <td>
                                    {@html exercice[field]}
                                    {#if field == "title" && exercice.wip}
                                        <Icon name="cone-striped" />
                                    {/if}
                                </td>
                            {/each}
                        </tr>
                    {/if}
                {/each}
            </tbody>
        </Table>
    {/await}
</Container>
