<script context="module">
 import { session } from '$app/stores';

 export function load() {
     if (session.id) {
         return { redirect: '/', status: 302 };
     }

     return { };
 }
</script>

<script>
 import { goto } from '$app/navigation';
 import { page } from '$app/stores'

 import AuthButton from '../components/AuthButton.svelte';

 let auth = { username: "", password: "" };
 let pleaseWait = false;

 export let next = $page.url.searchParams.get('next');

 function logmein() {
     pleaseWait = true;
     fetch('api/auth', {
	 method: 'POST',
	 body: JSON.stringify(auth),
     })
         .then((response) => {
             response.json().then((auth) => {
	         pleaseWait = false;
                 $session = auth;
                 if (next && next.indexOf('//') === -1) {
                     goto(next)
                 } else {
	             goto(".");
                 }
             })
         })
         .catch((response) => {
	     pleaseWait = false;
	     if (response.data)
                 ToastsStore.addToast({
	             color: "danger",
	             title: "Connexion impossible",
	             msg: (response.data ? response.data.errmsg : "Impossible de contacter le serveur"),
	         });
         });
 }
</script>

<div class="row">
    <form class="col" on:submit|preventDefault={logmein}>
        <h2>Accès à votre compte</h2>
        <div class="mb-3">
            <label for="login" class="form-label">CRI login</label>
            <input class="form-control" id="login" bind:value={auth.username} placeholder="Entrer votre login" autofocus>
        </div>
        <div class="mb-3">
            <label for="password" class="form-label">Mot de passe</label>
            <input type="password" class="form-control" id="password" bind:value={auth.password} placeholder="Mot de passe">
        </div>
        <button type="submit" class="btn btn-info">
            {#if pleaseWait}
                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
            {/if}
            Me connecter
        </button>
    </form>

    <div class="col">
        <h2>OpenId Connect</h2>
        <div class="text-center">
            <AuthButton class="btn btn-primary">
	        Me connecter avec mon compte CRI
            </AuthButton>
        </div>
    </div>
</div>
