<template>
  <div class="signup">
    <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="email">E-pasts</label>
      <input type="text" id="email" v-model.trim="email">
    </div>
    <div class="input-group">
      <label for="pass">Parole</label>
      <input type="password" id="pass" v-model.trim="password">
    </div>
    <button @click="signUp" class="btn btn-green btn-big border">Reģistrēties</button>
    <div :class="notice.error ? 'error-block' : 'success-block'" v-if="notice.display" @click="notice.display = false">
      <span>{{ notice.text }}</span>
    </div>
  </div>
</template>

<script>
import { Auth } from 'aws-amplify';

export default {
  props: {
    errors: Object
  },
  data() {
    return {
      username: '',
      password: '',
      email: '',
      notice: {
        error: false,
        text: '',
        display: false
      }
    }
  },
  methods: {
    signUp() {
      const { username, password, email, displayError, displaySuccess } = this;
      const passRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[ !"#$%&'()*+,-./:;<=>?@[\]\\^_`{|}~])[A-Za-z\d !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]{8,}$/;
      const emailRegex = /^[A-Za-z0-9-_.]+@[A-Za-z0-9-_.]+\.[A-Za-z0-9-_.]+$/;

      if (username === '' || password === '' || email === '') {
        displayError('Pārliecinieties, lai visi lauki būtu aizpildīti!');
      } else if (!emailRegex.test(email)) {
        displayError('Nepareizs e-pasta formāts');
      } else if (!passRegex.test(password)) {
        displayError('Parolei jābūt vismaz 8 rakstzīmju garai. Tai jāsastāv no vismaz viena mazā burta, lielā burta, cipara un simbola');
      } else {
        Auth.signUp({
          username,
          password,
          attributes: { email }
        }).then(() => {
          displaySuccess('Uz jūsu e-pastu tika nosūtīta saite, lai apstiprinātu reģistrēšanos');
        }).catch(error => {
          displayError(this.errors[error.code] || 'Radās kļūda!');
        });
      }
    },
    displayError(text) {
      this.notice.error = true;
      this.notice.text = text;
      this.notice.display = true;
    },
    displaySuccess(text) {
      this.notice.error = false;
      this.notice.text = text;
      this.notice.display = true;
    }
  }
}
</script>