<script>
 import {
     Alert,
     Button,
     Card,
     CardBody,
     CardHeader,
     Container,
     Icon,
     Table,
 } from '@sveltestrap/sveltestrap';

 import DateFormat from '$lib/components/DateFormat.svelte';

 import { issues, issues_nb_responses, issues_known_responses } from '$lib/stores/issues.js';
 import { settings } from '$lib/stores/settings.js';

 import FormIssue from '$lib/components/FormIssue.svelte';

 // Override theme color
 document.body.style.backgroundColor = "";

 export let data;
 let issue = {};

 issues_known_responses.set($issues_nb_responses);

 function newIssue() {
     data.fillIssue = true;
 }

 let sberr = "";
 let message = "";
 let messageClass = "success";

 function waitDiff(curissues, i) {
     issues.refresh((issues) => {
         if (i > 0 && (!issues || issues.length <= curissues)) {
             setTimeout(waitDiff, 850, curissues, i-1);
         }
     })
 }

 function respondTo(_issue) {
     data.exercice = null;
     issue = {id: _issue.id, description: ''};
     data.fillIssue = true;
 }

 async function submit_issue(event) {
     sberr = "";
     if (!issue.id && issue.subject.length < 3) {
	 messageClass = "warning";
	 sberr = "L'objet de votre rapport d'anomalie est trop court !";
	 return false;
     }

     const response = await fetch('issue', {
	 method: "POST",
         headers: {'Accept': 'application/json'},
	 body: JSON.stringify(issue),
     });

     if (response.status < 300) {
         const data = await response.json();
	 messageClass = 'success';
	 message = data.errmsg;
         issue = { };
         data.exercice = null;
         data.fillIssue = false;

         const currentissues = get_store_value(issues);
         waitDiff(currentissues.length, 7);
     } else {
	 messageClass = 'danger';

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

	 if (data && data.errmsg)
	     message = data.errmsg;
	 if (response.statys != 402)
	     sberr = "Une erreur est survenue lors de l'envoi. Veuillez réessayer dans quelques instants.";
     }
 }
</script>

<Container fluid class="my-3">
{#if message || sberr}
    <Alert color={messageClass} fade={false}>
        {#if !sberr}
            <strong>Votre rapport a bien été envoyé&nbsp;!</strong>
        {:else}
            <strong>{sberr}</strong>
        {/if}
        {message}
    </Alert>
{/if}

{#if data.fillIssue}
    <Card class="border-warning mt-3 mb-5">
        <CardHeader class="bg-warning text-light">
            <Icon name="file-earmark-plus" />
            {#if issue.id}
                Répondre à un message
            {:else}
                Rapporter une anomalie sur un défi
            {/if}
        </CardHeader>
        <CardBody>
            {#if !$settings.acceptNewIssue}
                <p class="card-text">Rapprochez-vous d'un membre de l'équipe afin d'obtenir de l'aide.</p>
            {:else}
                <FormIssue
                    exercice={data.exercice}
                    bind:issue={issue}
                    on:submit={submit_issue}
                />
            {/if}
        </CardBody>
    </Card>
{/if}

<Card>
    <Table hover striped>
        <thead>
            <tr>
	        <th>Objet</th>
	        <th>État / Priorité</th>
	        <th>Géré par</th>
	        <th>Messages</th>
	        <th>
                    {#if !data.fillIssue}
	                <Button size="sm" color="warning" on:click={newIssue}>
                            <Icon name="file-earmark-plus" />
                        </Button>
                    {/if}
                </th>
            </tr>
        </thead>
        <tbody>
            {#each $issues as issue (issue.id)}
            <tr>
	        <td>
                    {issue.subject}
                    {#if issue.exercice} (défi <a href="{issue.url}">{issue.exercice}</a>){/if}
                </td>
	        <td>{issue.state} / {issue.priority}</td>
	        <td>{#if issue.assignee}{issue.assignee}{:else}En attente d'attribution{/if}</td>
	        <td>
                    {#each issue.texts as text, index}
	                <p style="margin-left: 15px; text-indent: -15px">
                            {#if !text.assignee || text.assignee == '$team'}Vous{:else}{text.assignee}{/if}
	                    le <DateFormat date={text.date} />&nbsp;:
	                    <span style="white-space: pre-line">{text.cnt}</span>
	                </p>
                    {/each}
	        </td>
	        <td>
	            <Button
                        size="sm"
                        color={issue.state == 'need-info'?'danger':'light'}
                        on:click={respondTo(issue)}
                    >
                        <Icon name={issue.state == 'need-info'?'envelope-fill':'envelope-open-fill'} />
                    </Button>
	        </td>
            </tr>
            {:else}
            <tr>
                <td colspan="5" class="text-center py-2">
                    Aucune anomalie remontée pour l'instant.<br>
                    Vous souhaitez nous faire <a href="issues?fill-issue">remonter un problème</a>&nbsp;?
                </td>
            </tr>
            {/each}
        </tbody>
    </Table>
</Card>
</Container>
