<script context="module">
 import CorrectionPieChart from '$lib/components/CorrectionPieChart.svelte';
 import { getSurvey } from '$lib/surveys';
 import { getUsers } from '$lib/users';

 export async function load({ params, stuff }) {
     return {
         props: {
             surveyP: stuff.survey,
         },
     };
 }
</script>

<script lang="ts">
 import { goto } from '$app/navigation';

 import { user } from '$lib/stores/user';
 import StartStopLiveSurvey from '$lib/components/StartStopLiveSurvey.svelte';
 import SurveyAdmin from '$lib/components/SurveyAdmin.svelte';
 import SurveyBadge from '$lib/components/SurveyBadge.svelte';
 import SurveyQuestions from '$lib/components/SurveyQuestions.svelte';
 import { getQuestions } from '$lib/questions';

 export let surveyP;
 let usersP = null;
 surveyP.then((s) => {
     usersP = getUsers(s.promo, s.group);
 })
 let edit = false;
 let exportview = false;
 let exportview_list = false;

 let sharing_link = null;
 async function shareResults(survey) {
     const res = await survey.share();
     sharing_link = res;

     const modal = new bootstrap.Modal(document.getElementById('shareModal'));
     modal.show();
 }
</script>

{#await surveyP then survey}
    {#if $user && $user.is_admin}
        <button class="btn btn-primary ms-1 float-end" on:click={() => { edit = !edit; } } title="Éditer"><i class="bi bi-pencil"></i></button>
        <StartStopLiveSurvey
            {survey}
            class="ms-1 float-end"
            on:update={() => goto(`surveys/${survey.id}/admin`)}
        />
        <button
            class="btn btn-outline-dark ms-1 float-end"
            title="Partager les résultats"
            on:click={() => shareResults(survey)}
        ><i class="bi bi-share-fill"></i></button>
        <button
            class="btn ms-1 float-end"
            class:btn-dark={exportview}
            class:btn-outline-dark={!exportview}
            title="Afficher les graphiques"
            on:click={() => { exportview = !exportview; } }
        ><i class="bi bi-activity"></i></button>
        {#if exportview}
            <button
                class="btn ms-1 float-end"
                class:btn-dark={exportview_list}
                class:btn-outline-dark={!exportview_list}
                title="Traiter les listes comme des textes : ne pas chercher à les regrouper sous un diagramme"
                on:click={() => { exportview_list = !exportview_list; } }
            ><i class="bi bi-view-list"></i></button>
        {/if}
    {/if}
    <div class="d-flex align-items-center">
        <h2>
            <a href="surveys/{survey.id}" class="text-muted" style="text-decoration: none">&lt;</a>
            {survey.title}
            <small class="text-muted">{#if exportview}Réponses{:else}Corrections{/if}</small>
        </h2>
        <SurveyBadge class="ms-2" {survey} />
    </div>

    {#if $user && $user.is_admin && edit}
        <SurveyAdmin {survey} on:saved={() => edit = false} />
    {/if}

    {#await getQuestions(survey.id)}
        <div class="text-center">
            <div class="spinner-border text-primary mx-3" role="status"></div>
            <span>Chargement des questions &hellip;</span>
        </div>
    {:then questions}
        {#if !exportview}
            <div class="card mt-3 mb-5">
                <table class="table table-hover table-striped mb-0">
                    <thead>
                        <tr>
                            <th>Question</th>
                            <th>Réponses</th>
                            <th>Moyenne</th>
                        </tr>
                    </thead>
                    <tbody ng-controller="SurveyGradesController">
                        {#each questions as question (question.id)}
                            <tr>
                                <td><a href="surveys/{survey.id}/responses/{question.id}">{question.title}</a></td>
                                {#await question.getResponses()}
                                    <td colspan="2" class="text-center">
                                        <div class="spinner-border mx-3" role="status"></div>
                                        <span>Chargement &hellip;</span>
                                    </td>
                                {:then responses}
                                    <td>
                                        {#if responses}
                                            {responses.filter((r) => !r.time_scored || (r.time_reported && r.time_reported >= r.time_scored)).length} /
                                            {responses.length}
                                            {#await usersP then users}
                                                <br>
                                                {Math.trunc(responses.length/users.length*1000)/10}&nbsp;%
                                            {/await}
                                {:else}
                                            0
                                        {/if}
                                    </td>
                                    <td>
                                        {#if responses && responses.filter((r) => r.time_scored).length}
                                            {Math.trunc(responses.reduce((p, c) => (p + (c.score?c.score:0)), 0)/responses.filter((r) => r.time_scored).length*10)/10}&nbsp;%
                                        {:else}
                                            --&nbsp;%
                                        {/if}
                                    </td>
                                {/await}
                            </tr>
                        {/each}
                    </tbody>
                </table>
            </div>
        {:else}
            {#each questions as question (question.id)}
                <h3>{question.title}</h3>
                {#if question.kind == "text" || (exportview_list && question.kind.indexOf("list") == 0)}
                    {#await question.getResponses() then responses}
                        {#each responses as response (response.id)}
                            <div class="card mb-2">
                                <div class="card-body">
                                    <p class="card-text" style:white-space="pre-line">
                                        {response.value}
                                    </p>
                                </div>
                            </div>
                        {/each}
                    {/await}
                {:else}
                    <CorrectionPieChart {question} />
                {/if}
                <hr class="mb-3">
            {/each}
        {/if}
    {/await}
{/await}

<div class="modal fade" tabindex="-1" id="shareModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Partage de résultats</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>
                    Voici le lien de partage des résultats de ce sondage&nbsp;:
                </p>
                <pre>{sharing_link}</pre>
            </div>
        </div>
    </div>
</div>
