<template>
    <v-card flat>
        <v-form ref="form" v-model="valid">
            <v-card-text>
                <v-text-field
                    v-model="form.username"
                    :rules="usernameRules"
                    label="Username"
                    required
                    :prepend-icon="mdiAccount"
                ></v-text-field>

                <v-text-field
                    v-model="form.password"
                    :rules="passwordRules"
                    label="Password"
                    required
                    :prepend-icon="mdiLock"
                    type="password"
                ></v-text-field>

                <v-text-field
                    v-model="confirm"
                    :rules="confirmRules"
                    label="Confirm your password"
                    required
                    :prepend-icon="mdiLock"
                    type="password"
                ></v-text-field>
            </v-card-text>
            <v-card-actions>
                <v-spacer />
                <v-btn
                    :disabled="!valid"
                    color="success"
                    type="submit"
                    @click.prevent="registerUser"
                >
                    Register
                </v-btn>
            </v-card-actions>
        </v-form>
    </v-card>
</template>

<script>
import { mdiAccount, mdiAt, mdiLock } from '@mdi/js'

export default {
    name: 'RegisterForm',
    data: (vm) => ({
        mdiLock,
        mdiAccount,
        mdiAt,
        valid: false,
        form: {
            username: '',
            password: '',
        },
        usernameRules: [
            (v) => !!v || 'Username is required',
            (v) =>
                v.length <= 50 ||
                'Username must be shorter or equal to 50 characters',
            (v) =>
                v.length >= 3 ||
                'Username must be longer or equal to 3 characters',
        ],
        passwordRules: [
            (v) => !!v || 'Password is required',
            (v) =>
                v.length >= 6 ||
                'Password must be longer or equal to 6 characters',
        ],
        confirm: '',
        confirmRules: [
            (v) => !!v || 'Password is required',
            (v) => v === vm.form.password || 'Both passwords must be equals',
        ],
    }),
    methods: {
        registerUser() {
            this.$axios
                .post('/user', this.form)
                .then(() => this.$root.$emit('register::success'))
                .catch(() =>
                    this.$root.$emit(
                        'toast',
                        'Please choose another username',
                        'error'
                    )
                )
        },
    },
}
</script>
