<template>
  <v-dialog v-model="dialog">
    <v-btn slot="activator">
      Register
    </v-btn>

    <v-card>
      <v-form
        ref="form"
        v-model="valid"
        @submit.prevent="validate"
        lazy-validation
      >
        <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-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>

          <v-btn color="success" type="submit" :disabled="!valid">
            Register
          </v-btn>

          <v-btn color="error" @click="dialog = false">
            Cancel
          </v-btn>
        </v-card-actions>
      </v-form>
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  name: 'RegisterForm',
  data: () => ({
    dialog: false,
    valid: true,

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

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

  methods: {
    validate() {
      if (this.$refs.form.validate()) {
        window.pkgs.axios
          .post('/user/register', {
            login: this.login,
            password: this.password
          })
          .then(response => {
            // this.$refs.form.reset()
            console.log('register', response.data)
          })
      }
    }
  },

  watch: {
    dialog(val) {
      if (val)
        requestAnimationFrame(() => {
          this.$refs.autofocus.focus()
        })
    }
  }
}
</script>
