<template>
    <div>
        <v-container align="center" justify="center">
            <v-layout row> 
                <v-flex md4>
                    <v-card
                        v-for="user in users"
                        :key="user.username"
                    >
                        <v-card-title><v-icon>{{ user_icon(user) }}</v-icon>&nbsp;&nbsp;&nbsp;{{ user.fullname }} ({{ user.username }})</v-card-title>
                        <v-card-subtitle><font :color="user_color(user)">{{ user_state(user) }}</font></v-card-subtitle>
                        <v-layout col>
                            <v-flex md6>
                                <v-autocomplete
                                    :items="acount_states"
                                    color="white"
                                    item-text="name"
                                    v-model="item_right"
                                    item-color="color"
                                    return-object
                                    label="Droits"
                                    @change="user_right_request_change(user)"
                                ></v-autocomplete>
                                <v-btn @click="save_user(user)">Sauvegarder</v-btn>
                            </v-flex>
                        </v-layout>
                    </v-card>
                </v-flex>
            </v-layout>
        </v-container>
    </div>
</template>

<script>
import {account_type_text} from '@/utils/utils'
import axios from 'axios'
export default {
    data () {
        return {
            item_right: null,
            acount_states: [
                {name: 'Banni', access: -1, color: 'dark-red'},
                {name: 'Utilisateur', access: 0, color: 'white'},
                {name: 'Observateur', access: 1, color: 'white'},
                {name: 'Administrateur', access: 2, color: 'red'}
            ]
        }
    },
    mounted() {
        this.$store.dispatch('fetch_users')
    },
    computed: {
        users () {
            return this.$store.state.users
        }
    },
    methods: {
        save_user (user) {
            console.log(user.changes)
            axios.put(`/users/${user.username}`, user.changes)
            .then((resp) => {
                this.$store.dispatch('fetch_users')
            })
            .catch((err) => {
                this.$store.commit('display_error', err)
            })
        },
        user_icon (user) {
            return account_type_text(user.access).icon
        },
        user_state (user) {
            return account_type_text(user.access).text
        },
        user_color (user) {
            return account_type_text(user.access).color
        },
        user_right_request_change (user) {
            user.changes.access = this.item_right.access
        }
    }
}
</script>