<script>
 import DateFormat from '../components/DateFormat.svelte';
 import { WorkRepository, getRemoteRepositories, getRepositories } from '../lib/repositories';
 import { ToastsStore } from '../stores/toasts';

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

 export let work = {};
 export let readonly = false;

 let repo_work = null;
 let repo_used = null;
 let remote_repos = [];

 function refresh_repo_work() {
     repo_work = getRepositories(work.id);
     repo_work.then((repos) => {
         repo_used = repos[0];
     }, () => {
         repo_used = new WorkRepository({id_work: work.id});
         remote_repos = getRemoteRepositories();
     });
 }
 refresh_repo_work();

 let submitInProgress = false;
 function submitWorkRepository() {
     submitInProgress = true;
     repo_used.save().then(() => {
	 submitInProgress = false;
         refresh_repo_work();
     }, (error) => {
	 submitInProgress = false;
         ToastsStore.addErrorToast({
             msg: "Une erreur s'est produite durant la création de la liaison au dépôt : " + error,
         });
     });
 }
</script>

{#await repo_work}
    <div class="{className} text-center">
        <div class="spinner-border text-primary mx-3" role="status"></div>
        <span>Chargement de vos préférences de rendu &hellip;</span>
    </div>
{:then repos}
    {#each repos as repo (repo.id)}
        <div class="{className} card">
            <div class="card-body d-flex justify-content-between">
                <div class="d-flex flex-column justify-content-center">
                    <div>
                        Dépôt lié&nbsp;: <strong style="font-family: monospace">{repo.uri}</strong><br>
                        Dernière récupération&nbsp;: <strong>{#if repo.last_check}<DateFormat date={new Date(repo.last_check)} dateStyle="medium" timeStyle="medium" />{:else}-{/if}</strong>
                    </div>
                </div>
                <div class="d-flex flex-column justify-content-center">
                    <button
                        type="button"
                        class="btn btn-outline-info float-end mb-1"
                        disable={submitInProgress || readonly}
                        on:click={() => repo.retrieveWork().then(() => { refresh_repo_work() }, (error) => ToastsStore.addErrorToast({msg: "Une erreur s'est produite : " + error}))}
                    >
                        Mettre à jour
                    </button>
                    <button
                        type="button"
                        class="btn btn-outline-danger float-end mt-1"
                        disable={submitInProgress || readonly}
                        on:click={() => repo.delete().then(() => { refresh_repo_work() }, (error) => ToastsStore.addErrorToast({msg: "Une erreur s'est produite durant la suppression du lien : " + error}))}
                    >
                        Supprimer cette liaison
                    </button>
                </div>
            </div>
        </div>
    {/each}
{:catch}
    {#if !readonly}
        <p>
            Voici la liste des dépôts reconnus&nbsp;:
        </p>
        <form class="{className} form-floating" on:submit|preventDefault={submitWorkRepository}>
            {#await remote_repos}
                <div class="text-center">
                    <div class="spinner-border text-primary mx-3" role="status"></div>
                    <span>Récupération de vos dépôts GitLab &hellip;</span>
                </div>
            {:then rrepos}
                <select class="form-select col" disabled={readonly} bind:value={repo_used.uri}>
                    {#each rrepos as r (r.Id)}
                        <option value={r.ssh_url_to_repo}>{r.path_with_namespace}</option>
                    {/each}
                </select>
                <label>Dépôt GitLab pour ce travail&nbsp;:</label>
            {/await}
            <button
                type="submit"
                class="mt-2 btn btn-primary"
                disable={submitInProgress || readonly}
            >
                Utiliser ce dépôt
            </button>
            <button
                type="button"
                class="mt-2 btn btn-info"
                title="Rafraîchir la liste des dépôts"
                on:click={() => remote_repos = getRemoteRepositories()}
            >
                <i class="bi bi-arrow-clockwise"></i>
            </button>
        </form>
    {/if}
{/await}
