<template>
  <div>
    <Header/>
    <form id="login_form" class="content login" @submit.prevent="authenticate">
      <input v-model="username" type="text" required placeholder="Nom de l'équipe" aria-label="Nom de l'équipe"/>
      <input id="code" v-model="password" type="password" required placeholder="Code" aria-label="Code"/>
      <div>
        <label>
          <input v-model="conditionChecked" type="checkbox" required/>
          En continuant, j’accepte les conditions d'utilisation de Boussole PLUSS et j’ai lu la politique de
          confidentialité
        </label>
      </div>
      <button class="button blue" type="submit" :disabled="!conditionChecked">
        Continuer
      </button>
      <div class="error-container">{{ error }}</div>
    </form>
  </div>
</template>

<script lang="ts">
import {Component, Vue} from "nuxt-property-decorator";
import {HTTPResponse} from "@nuxtjs/auth-next/dist";

@Component
export default class Login extends Vue {
  private username = "";
  private password = "";
  private conditionChecked: boolean = false;
  private error = "";

  async authenticate() {
    try {
      this.error = "";
      const response = await this.$auth.loginWith('local', {
        data: {
          username: this.username,
          password: this.password
        }
      }) as HTTPResponse;
      if (response && response.data) {
        const { token } = response.data;
        this.$axios.defaults.headers.common = { Authorization: `Bearer ${token}` };
      } else {
        console.error("Unable to login, no data in HTTP response")
      }
    } catch (e: any) {
      this.error = e;
      console.info("error", e);
    }
  }
}
</script>

<style lang="scss" scoped>

@import "assets/css/spacing";

form.login {
  input[type="text"] {
    margin: $x_small 0;
  }

  input[type="password"] {
    margin-bottom: $small;
  }

  button {
    margin: $medium 0;
  }
}

.error-container {
  display: flex;
  justify-content: center;
  color: red;
}

</style>
