<script>
 import { user } from '../stores/user';
 import { ToastsStore } from '../stores/toasts';
 import QuestionForm from '../components/QuestionForm.svelte';
 import { Question } from '../lib/questions';

 export let survey = null;
 export let id_user = null;
 export let questions = [];
 let newquestions = [];
 let submitInProgress = false;

 function submitAnswers() {
     submitInProgress = true;

     const res = [];
     for (const r in responses) {
	 res.push({"id_question": responses[r].id_question, "value": String(responses[r].value)})
     }

     survey.submitAnswers(res, id_user).then((response) => {
	 submitInProgress = false;
         ToastsStore.addToast({
             msg: "Vos réponses ont bien étés sauvegardées.",
             color: "success",
             title: "Questionnaire",
         });
     }, (error) => {
	 submitInProgress = false;
         ToastsStore.addErrorToast({
             msg: "Une erreur s'est produite durant l'envoi de vos réponses : " + error + "\nVeuillez réessayer dans quelques instants.",
         });
     });
 }

 function addQuestion() {
     const q = new Question();
     q.id_survey = survey.id;
     newquestions.push(q);
     newquestions = newquestions;
 }

 function deleteQuestion(question, qid) {
     question.delete().then(() => {
         questions.splice(qid, 1);
         questions = questions;
     })
 }

 function deleteNewQuestion(question, qid) {
     if (question.id) {
         question.delete().then(() => {
             newquestions.splice(qid, 1);
             newquestions = newquestions;
         })
     } else {
         newquestions.splice(qid, 1);
         newquestions = newquestions;
     }
 }

 let responses = {};
 for (const q of questions) {
     responses[q.id] = {id_question: q.id, value: ""};
 }
 survey.retrieveAnswers(id_user).then((response) => {
     if (response) {
         for (const res of response.reverse()) {
             responses[res.id_question] = res;
         }
     }
 })
</script>

<form class="mb-5" on:submit|preventDefault={submitAnswers}>
    {#each questions as question, qid (question.id)}
        <QuestionForm
            {survey}
            qid={qid}
            question={question}
            response_history={responses[question.id]}
            readonly={survey.isFinished() && !$user.is_admin}
            on:delete={() => deleteQuestion(question, qid)}
            bind:value={responses[question.id].value}
        />
    {/each}
    {#each newquestions as question, qid (qid)}
        <QuestionForm
            qid={questions.length + qid}
            question={question}
            edit
            on:delete={() => deleteNewQuestion(question, qid)}
        />
    {/each}

    <div class="d-flex justify-content-between">
        {#if !survey.corrected || $user.is_admin}
            <button type="submit" class="btn btn-primary" disabled={submitInProgress || (survey.isFinished() && !$user.is_admin)}>
                {#if submitInProgress}
                    <div class="spinner-border spinner-border-sm me-1" role="status"></div>
                {/if}
                Soumettre les réponses
            </button>
        {/if}
        {#if $user && $user.is_admin}
            <button type="button" class="btn btn-info" on:click={addQuestion}>
                Ajouter une question
            </button>
        {/if}
    </div>
</form>
