<script>
export default {
    computed: {
        dashboard () { 
            return this.$store.state;
        }
    },
    data() {
        return {
            error: [],
            login: {
                user: "", 
                password: ""
            },
            showPassword: false
        }
    },
    mounted () {
        this.$store.commit("setTitle", "Login");
    },
    methods: {
        formSubmit (e) {
            e.preventDefault();
            fetch("/api/v1/user/login", {method: "POST", body: JSON.stringify(this.$data.login)})
                .then(x => x.json())
                .then(x => {
                    this.$data.error = ""
                    this.$store.commit("setToken", x.token);
                })
                .catch(x => this.$data.error = ["The entered credentials are invalid!"]);

            // TODO display invalidCredentials
            // TODO redirect to dashboard on success
        }
    }
}
</script>

<template>
    <v-container>
        <v-row>
            <v-col cols="12">
                <v-text-field v-model="login.user" type="text" label="Username" />
            </v-col>
            <v-col cols="12">
                <v-text-field v-model="login.password" label="Password"
                    :append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'" 
                    :type="showPassword ? 'text' : 'password'"
                    @click:append="showPassword = showPassword"
                    :error-message="error"
                    error-count="2"
                    error />
            </v-col>
        </v-row>
        <div class="form-group">
            {{ error }}
        </div>
        <v-btn type="submit" @click="formSubmit">Login</v-btn>
        <p>
	        New user? <router-link to="/register">Register</router-link> instead!
        </p>
    </v-container>
</template>