<template>
  <div class="signin">
    <template v-if="!forgotPass">
      <div class="input-group">
        <label for="user">Lietotājvārds</label>
        <input type="text" id="user" v-model.trim="username">
      </div>
      <div class="input-group">
        <label for="pass">Parole</label>
        <input type="password" id="pass" v-model.trim="password">
      </div>
      <button @click="signIn" class="btn btn-green btn-big border">Pieslēgties</button>
      <button @click="forgotPass = true" class="btn btn-slim">Aizmirsu paroli</button>
      <div :class="notice.error ? 'error-block' : 'success-block'" v-if="notice.display" @click="notice.display = false">
        <span>{{ notice.text }}</span>
      </div>
    </template>
    <ForgotPassword v-else :errors="errors" @back-to-signin="backToSignIn" />
  </div>
</template>

<script>
import { Auth } from 'aws-amplify';
import ForgotPassword from '@/components/ForgotPassword';

export default {
  props: {
    errors: Object
  },
  components: {
    ForgotPassword
  },
  data() {
    return {
      username: '',
      password: '',
      forgotPass: false,
      notice: {
        error: false,
        text: '',
        display: false
      }
    }
  },
  methods: {
    signIn() {
      const { username, password, displayError } = this;

      if (username === '' || password === '') {
        displayError('Pārliecinieties, lai visi lauki būtu aizpildīti!');
      } else {
        Auth.signIn({
          username,
          password
        }).catch(error => {
          displayError(this.errors[error.code] || 'Radās kļūda!');
        });
      }
    },
    backToSignIn() {
      this.forgotPass = false;
    },
    displayError(text) {
      this.notice.error = true;
      this.notice.text = text;
      this.notice.display = true;
    }
  }
}
</script>