<template>
  <div>
    <form novalidate @submit.prevent="performRegister" @input="duplicate = false">
      <md-card-content>
        <md-content class="text-alert" v-if="duplicate">Username already taken</md-content>
        <md-field>
          <label>Username</label>
          <md-input v-model="form.name" :disabled="authInProgress"></md-input>
        </md-field>

        <md-field :md-toggle-password="false">
          <label>Password</label>
          <md-input v-model="form.password" type="password" :disabled="authInProgress"></md-input>
        </md-field>

        <md-field :md-toggle-password="false">
          <label>Confirm password</label>
          <md-input v-model="form.passwordConfirm" :disabled="authInProgress" type="password"></md-input>
        </md-field>

      </md-card-content>

      <md-card-actions>
        <md-progress-spinner :md-diameter="30" :md-stroke="3" md-mode="indeterminate" v-if="authInProgress"
                             class="md-accent"/>
        <md-button type="submit" class="md-primary" :disabled="authInProgress || !passwordGood">Register
        </md-button>
      </md-card-actions>
    </form>
  </div>
</template>

<script>
import {mapGetters} from "vuex";

export default {
  name: "Register",
  data() {
    return {
      form: {
        name: "",
        password: "",
        passwordConfirm: ""
      },
      duplicate: false
    }
  },
  methods: {
    performRegister() {
      const creds = {name: this.form.name, password: this.form.password};
      this.$store.dispatch("auth/performRegister", creds).then(() => {
        this.$router.push({name: 'Dashboard'});
      }).catch(() => {
        // Interpret any error returned by the server as conflict
        this.duplicate = true;
      })
    }
  },
  computed: {
    ...mapGetters('auth', ['authInProgress']),
    passwordGood() {
      return this.form.password !== "" && this.form.password === this.form.passwordConfirm;
    }
  }
}
</script>

<style scoped>
.text-alert {
  color: red !important;
  font-weight: bold;
}
</style>