<script>
    import { getToken } from "../../services/auth";

    let form = {}
    let loading = false;

    async function onSubmit() {
        try {
            loading = true;
            const data = await getToken(form)
            sessionStorage.setItem('usuario', JSON.stringify(data))
            document.location.reload()
        } catch (error) {
            alert(error.message || error)
        } finally {
            loading = false;
        }
    }
</script>

<svelte:head>
    <title>Login</title>
</svelte:head>

<h1>Login</h1>
<div>
    {#if loading}
        <p>Espere un momento...</p>
    {/if}
    
    <form action="" on:submit|preventDefault={() => onSubmit()}>
        <div>
            <label for="">Usuario</label>
            <input type="text" bind:value={form.username}>
        </div>
        <div>
            <label for="">Contraseña</label>
            <input type="password" bind:value={form.password}>
        </div>
        <button>Acceder</button>
    </form>
</div>