<template>
  <FormDialog ref="main" buttonText="Register" @validated="doRegister">
    <v-card-title class="headline">
      Register
    </v-card-title>

    <v-card-text>
      <v-text-field
        ref="autofocus"
        v-model="login"
        :rules="loginRules"
        label="User name"
        required
      ></v-text-field>

      <v-text-field
        v-model="password"
        :append-icon="showPassword ? 'visibility' : 'visibility_off'"
        @click:append="showPassword = !showPassword"
        :rules="passwordRules"
        :type="showPassword ? 'text' : 'password'"
        label="Password"
        required
        counter
      ></v-text-field>

      <v-text-field
        v-if="!showPassword"
        v-model="passwordConfirm"
        :rules="passwordConfirmRules"
        :type="showPassword ? 'text' : 'password'"
        label="Confirm Password"
        required
      ></v-text-field>
    </v-card-text>
  </FormDialog>
</template>

<script>
import FormDialog from './FormDialog.vue'
import axios from '@/plugins/axios'

export default {
  name: 'RegisterForm',

  components: {
    FormDialog
  },

  data: () => ({
    login: '',
    loginRules: [v => !!v || 'User name is required'],

    password: '',
    showPassword: false,
    passwordRules: [v => !!v || 'Password is required'],

    passwordConfirm: ''
  }),

  computed: {
    passwordConfirmRules() {
      return [
        () => this.password === this.passwordConfirm || 'Passwords must match'
      ]
    }
  },

  methods: {
    doRegister() {
      axios
        .post('/user/register', {
          session: null,
          login: this.login,
          password: this.password
        })
        .then(response => {
          // this.$refs.form.reset()
          console.log('register', response.data)
          if (response.data.success) {
          } else {
            this.$refs.main.showError(response.data.message)
          }
        })
    }
  }
}
</script>
