<template>
  <div class="md-layout md-alignment-center-center" style="height: 100vh;">
    <md-card class="md-layout-item md-size-50">
      <md-card-header>
        <div class="md-title">
          Register
        </div>
      </md-card-header>

      <form @submit.prevent="resisterUser">
        <md-card-content>
          <md-field md-clearable>
            <label for="email">Email</label>
            <md-input
              id="email"
              v-model="form.email"
              :disabled="loading"
              type="email"
              name="email"
              autocomplete="email"
            />
          </md-field>
          <md-field>
            <label for="password">password</label>
            <md-input
              id="password"
              v-model="form.password"
              :disabled="loading"
              type="password"
              name="password"
              autocomplete="password"
            />
          </md-field>
        </md-card-content>

        <md-card-actions>
          <md-button to="/login">
            Go To Login
          </md-button>
          <md-button class="md-primary md-raised" type="submit">
            Submit
          </md-button>
        </md-card-actions>
      </form>

      <md-snackbar :md-active.sync="isAuthenticated">
        {{ form.email }} was successfully registerd!
      </md-snackbar>
    </md-card>
  </div>
</template>

<script>
export default {
  middleware: 'auth',
  data: () => ({
    form: {
      email: '',
      password: ''
    }
  }),
  computed: {
    loading () {
      return this.$store.getters.loading
    },
    isAuthenticated () {
      return this.$store.getters.isAuthenticated
    }
  },
  watch: {
    isAuthenticated (value) {
      if (value) {
        setTimeout(() => this.$router.push('/'), 500)
      }
    }
  },
  methods: {
    async resisterUser () {
      await this.$store.dispatch('authenticateUser', {
        email: this.form.email,
        password: this.form.password,
        resturnSecureToken: true
      })
    }
  }
}
</script>
