<template>
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-xl-10 col-lg-12 col-md-9">
        <div class="card o-hidden border-0 shadow-lg my-5">
          <div class="card-body p-0">
            <div class="row">
              <div class="col-lg-6 d-none d-lg-block bg-login-image">
                <img src="../assets/img/log.png" class="img-fluid" alt="Responsive image">
              </div>
              <div class="col-lg-6">
                <div class="p-5">
                  <div class="text-center">
                    <h1 class="h4 text-gray-900 mb-4">Connectez-vous !</h1>
                  </div>
                  <form class="user" @submit="onSubmit">
                    <p id="message" style="color: red"></p>
                    <Input v-for="input in inputs" :key="input.id" :information="input"/>
                    <button type="submit" class="btn btn-primary btn-user btn-block">Connexion</button>
                  </form>
                  <hr>
                  <div class="text-center">
                    <router-link to="/signup">
                      <a class="small">Créer un compte</a>
                    </router-link>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Input from '@/components/Input'
  import bcrypt from 'bcryptjs'

  export default {
    name: 'Index',
    components: {
      Input
    },
    data() {
      return {
        // Données pour créer les inputs du form
        inputs: [
          { type: 'text', id: 'login', placeholder: 'Login' },
          { type: 'password', id: 'password', placeholder: 'Mot de passe' }
        ]
      }
    },
    methods: {
      onSubmit(evt) {
        evt.preventDefault()
        const form = document.forms[0]

        // Récupération de tous les utilisateurs
        fetch(this.$apiUrl + '/user', {
          method: 'GET'
        })
          .then(response => {
            if (response.status === 200) {
              return response.json()
            } else {
              throw new Error('Something went wrong on api server!')
            }
          })
          .then(data => {
            // Données de l'utilisateur {{ Login }}, undefined s'il n'existe pas
            const row = data[data.findIndex((e) => e.login == form.elements.login.value)]
            
            if (row !== undefined) {
              // Comparaison des mots de passe
              let areEqual = bcrypt.compareSync(form.elements.password.value, row.password)

              if (areEqual) {
                // Enregistrement du token et redirection
                this.getToken(row.login, row.password).then(token => {
                  localStorage.setItem('login', row.login)
                  localStorage.setItem('token', token)
                  window.location.href = "/#/home"
                });
              }
              else {
                document.querySelector('#message').innerHTML = "Mauvais mot de passe"
              }
            }
            else {
              document.querySelector('#message').innerHTML = "Login introuvable"
            }
          }).catch(error => {
            console.error(error)
          });
      },
      getToken(login, password) {
        return new Promise((resolve, reject) => {
          fetch(this.$apiUrl + '/login', {
            method: 'POST',
            body: JSON.stringify({ login: login, password: password })
          })
            .then(response => {
              if (response.status === 200) {
                return response.json()
              } else {
                throw new Error('Something went wrong on api server!')
              }
            })
            .then(data => {
              // Envoie du token
              resolve(data.jwt_token)
            }).catch(error => {
              console.error(error)
              console.error(reject)
            });
        })
      }
    }
  }
</script>