<script setup>
  import { ref, computed } from 'vue'
  import { postLogin, extractFormErrorFromField, extractGlobalFormError } from './api.js'
  import { useRouter } from 'vue-router'
  import { useAuthStore } from './auth.store.js'

  const router = useRouter();

  const user = ref({
    username: "",
    password: ""
  });

  const errors = ref(null)

  const formError = computed(() => {
    return extractGlobalFormError(errors.value);
  })
  const userError = computed(() => {
    return extractFormErrorFromField("Username", errors.value);
  })
  const passwordError = computed(() => {
    return extractFormErrorFromField("Password", errors.value);
  })

  async function onSubmit(e) {
    const res = await postLogin(user)
    if (res.ok) {
      let json = await res.json();
      await login(user.value.username, json);
      router.push('/');
      return;
    } else {
      res.json().then((json) => (errors.value = json));
    }
  }

  async function login(username, json) {
    useAuthStore().login({username: username, token: json["token"]})
  }
</script>


<template>
  <div v-if="formError" class="notification is-danger">
    <p>{{formError}}</p>
  </div>
  <h1 class="title">{{$t('login.title')}}</h1>
  <form class="box" @submit.prevent="onSubmit">
    <div class="field">
      <label class="label">{{$t('login.username')}}</label>
      <div class="control">
        <input :class="'input ' + (userError ? 'is-danger' : '')" type="text" minlength="2" maxlength="20"
        required v-model="user.username" :placeholder="$t('login.username')">
      </div>
      <p v-if="userError" class="help is-danger">{{userError}}</p>
    </div>
    <div class="field">
      <label class="label">{{$t('login.password')}}</label>
      <div class="control">
        <input :class="'input ' + (passwordError ? 'is-danger' : '')" type="password" minlength="6"
        maxlength="100" v-model="user.password" required :placeholder="$t('login.password')">
      </div>
      <p v-if="passwordError" class="help is-danger">{{passwordError}}</p>
    </div>
    <div class="field">
      <div class="control">
        <button class="button is-link">{{$t('login.login')}}</button>
      </div>
    </div>
  </form>
</template>

<style scoped></style>
