<script>
 import {
     Button,
     Card,
     CardBody,
     CardHeader,
     CardText,
     Icon,
     ListGroup,
     ListGroupItem,
     Spinner,
 } from 'sveltestrap';

 import FlagKey from './FlagKey.svelte';
 import FlagMCQ from './FlagMCQ.svelte';

 export let exercice = { };
 export let flags = [];

 export let refresh_my;
 export let refresh_teams;

 function waitDiff(i) {
     refresh_my((my) => {
         if (my && my.exercices[exercice.id].tries != exercice.tries) {
             submitInProgress = false;
             refresh_teams();
         } else if (i > 0) {
             setTimeout(waitDiff, 450, i-1);
         }
     })
 }

 let responses = { };
 async function submitFlags() {
     submitInProgress = true;
     sberr = "";
     message = "";

     const response = await fetch(
         "/submit/" + exercice.id,
         {
             method: "POST",
             body: JSON.stringify(responses),
         }
     )

     if (response.status < 300) {
         const data = await response.json();
	 messageClass = 'text-success';
	 message = data.errmsg;
         waitDiff(20);
     } else {
         submitInProgress = false;

	 messageClass = 'text-danger';

         let data = "";
         try {
             data = await response.json();
         } catch(e) {
             data = null;
         }

	 if (data && data.errmsg)
	     message = data.errmsg;
	 if (response.statys != 402)
	     sberr = "Oups !";
     }
 }

 function resetResponses() {
     responses = {
         flags: { },
         mcqs: { },
         justifications: { },
     };
 }

 let last_exercice = null;
 $: {
     if (!last_exercice || last_exercice != exercice.id) {
         last_exercice = exercice.id;
         resetResponses()
     }
 }

 let sberr = "";
 let message = "";
 let messageClass = "text-danger";
 let timeouted = false;
 let submitInProgress = false;
</script>

<Card class="border-danger mb-2">
    <CardHeader class="bg-danger">
        <Icon name="flag-fill" />
        Faire son rapport
    </CardHeader>
    {#if exercice.tries || exercice.submitted || sberr}
        <ListGroup>
            {#if exercice.solved_time && exercice.tries}
                <ListGroupItem class="text-warning">
                    {exercice.tries} {exercice.tries==1?"tentative effectuée":"tentatives effectuées"}.
                    Dernière solution envoyée à {exercice.solved_time}.
                </ListGroupItem>
            {/if}
            {#if exercice.solve_dist}
                <ListGroupItem>
                    {exercice.solve_dist} {exercice.solve_dist == 1?"réponse erronée":"réponses erronées"}.
                </ListGroupItem>
            {/if}
            {#if exercice.submitted || sberr}
	        <ListGroupItem class="{messageClass}">
                    {#if !sberr}
                        <strong>Votre solution a bien été envoyée !</strong>
                    {:else}
                        <strong>{sberr}</strong> {message}
                    {/if}
                </ListGroupItem>
            {/if}
            {#if timeouted}
	        <ListGroupItem class="text-danger">
                    <strong>Oops</strong>
                    La requête a dépassé le délai d'attente. Vous devriez réessayer dans quelques instant&hellip;
                </ListGroupItem>
            {/if}
        </ListGroup>
    {/if}
    {#if !exercice.submitted || sberr}
        <CardBody>
	    <form on:submit|preventDefault={submitFlags}>
                {#each flags as flag ((flag.type?flag.type:"i") + flag.id)}
                    {#if flag.type == "mcq"}
                        <FlagMCQ
                            exercice_id={exercice.id}
                            {flag}
                            {refresh_my}
                            bind:values={responses.mcqs}
                            bind:justifications={responses.justifications}
                        />
                    {:else}
                        <FlagKey
                            exercice_id={exercice.id}
                            {flag}
                            {refresh_my}
                            bind:value={responses.flags[flag.id]}
                        />
                    {/if}
                {/each}

		<div class="form-group mt-2">
		    <Button
                        type="submit"
                        color="danger"
                        disabled={submitInProgress}
                    >
                        {#if submitInProgress}
                            <Spinner size="sm" class="me-2" />
                        {/if}
                        Soumettre
                    </Button>
		</div>
            </form>
        </CardBody>
    {/if}
</Card>
