<script lang="ts">
 import Chart from 'svelte-frappe-charts';

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

 export let question = null;

 function refreshProposals() {
     let req = question.getProposals();

     req.then((proposals) => {
         const proposal_idx = { };
         for (const proposal of proposals) {
             data.labels.push(proposal.label);
             data.datasets[0].values.push(0);
             proposal_idx[proposal.id] = new String(data.labels.length - 1);
         }

         req_responses = question.getResponses();
         req_responses.then((responses) => {
             for (const res of responses) {
                 data.datasets[0].values[proposal_idx[res.value]] += 1;
             }
         });
     });

     return req;
 }
 let req_proposals = null;
 let req_responses = null;

 if (question.kind == "int") {
     req_responses = question.getResponses();
     req_responses.then((responses) => {
         const proposal_idx = { };
         for (const res of responses) {
             if (proposal_idx[res.value]) {
                 data.datasets[0].values[proposal_idx[res.value]] += 1;
             } else {
                 data.labels.push(res.value);
                 data.datasets[0].values.push(1);
                 proposal_idx[res.value] = new String(data.labels.length - 1);
             }
         }
     });
 } else {
     req_proposals = refreshProposals();
 }

 let data = {
     labels: [],
     datasets: [
         {
             values: []
         }
     ]
   };
</script>

<div class="{className}">
    {#await req_proposals}
        <div class="text-center mt-4">
            <div class="spinner-border text-primary mx-3" role="status"></div>
            <span>Récupération des propositions&hellip;</span>
        </div>
    {:then}
        {#await req_responses}
            <div class="text-center mt-4">
                <div class="spinner-border text-primary mx-3" role="status"></div>
                <span>Récupération des réponses&hellip;</span>
            </div>
        {:then}
            <Chart data={data} type="pie" maxSlices="9" />
        {/await}
    {/await}
</div>
