
<script>
  import FormField from "./FormField.svelte";
  import { user } from '$/client/stores.js';
  import { createEventDispatcher  } from 'svelte';
  import api from '$/client/api.js';
  import { log } from "$/client/logging.js";

  let form = {
    email: "",
    password: "",
    _valid: false,
    _errors: {},
    _rules: {
      email: 'required|email',
      password: 'required'
    }
  }

  const dispatch = createEventDispatcher();

  const complete_auth = async (new_user) => {
    user.update(u => new_user);
    dispatch('authenticated');
  }

  const authenticate = async () => {
    form = api.validate(form);

    if(form._valid) {
      let [status, data] = await api.post('/api/login', {
            'username': form.email,
            'password': form.password
          });

      if(status === 200) {
        log.debug("Calling complete auth from authenticate");
        await complete_auth(data);
      } else {
        form._errors.main = "Invalid Login. Try again.";
      }
    }
  }
</script>

<form action="/api/login" method="POST" data-testid="login-form">
  <card>
    <top>
      <h1>Login</h1>
      {#if form._errors.main}
        <error data-testid="login-error"> { form._errors.main }</error>
      {/if}
    </top>
    <middle>
      <FormField form={ form } field="email" label="Email">
        <input id="email" name="username" placeholder="Email" type="text" bind:value={ form.email}>
      </FormField>

      <FormField form={ form } field="password" label="Password">
        <input id="password" name="password" placeholder="Password" type="password" bind:value={ form.password }>
      </FormField>
    </middle>

    <bottom>
      <button-group>
        <button type="button" on:click|preventDefault={ () => dispatch('canceled')}>Cancel</button>
        <button data-testid="login-button" type="submit" on:click|preventDefault={ authenticate }>Login</button>
      </button-group>
    </bottom>
  </card>

  <section><a href="/client/#/register/">Not a member? Register.</a></section>
  <section><a href="/client/#/forgot/">Forgot your password?</a></section>
</form>
