<template>
  <div id="body">
    <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">
                      <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>
  </div>
</template>

<script>
  import { apiUrl } from '../assets/js/variables'
  import Input from '@/components/Input'
  import bcrypt from 'bcryptjs'

  export default {
    name: 'Login',
    components: {
      Input
    },
    data() {
      return {
        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]

        fetch(apiUrl, {
          method: 'GET'
        })
          .then(response => {
            if (response.status === 200) {
              return response.json()
            } else {
              throw new Error('Something went wrong on api server!')
            }
          })
          .then(data => {
            const row = data[data.findIndex((e) => e.login == form.elements.login.value)]
            
            let hash = bcrypt.hashSync(form.elements.password.value, 10)
            let isEqual = bcrypt.compareSync(row.password, hash)

            console.log(isEqual)
          }).catch(error => {
            console.error(error)
          });
      }
    }
  }
</script>