<template>
    <v-dialog v-model="editModal" persistent max-width="700">
        <v-card>
            <v-card-title>
                <v-row justify="end" class="pt-2"><v-hover v-slot="{ isHovering, props }"><v-icon size="small" v-bind="props" :color="isHovering ? 'grey-darken-1' : 'grey-lighten-1'" variant="plain" icon="mdi-close" @click="closeModal()"></v-icon></v-hover></v-row>
            </v-card-title>

            <v-card-text>

                <v-row class="d-flex pb-8">
                    <v-col align="center" cols="12" class="pb-0">
                        <v-avatar color="yellow-darken-1" size="80">
                            <v-icon size="50" icon="mdi-book-edit" color="white"></v-icon>
                        </v-avatar>
                    </v-col>
                    <v-col align="center" cols="12" style="font-size: 25px;color:#FDD835" class="pt-0 mt-0"><strong>Edit Tool</strong></v-col>
                </v-row>

                <v-row wrap no-gutters>
                    <v-col cols="5" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                    <v-col cols="2" class="text-center">
                        Tool Info
                    </v-col>
                    <v-col cols="5" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                </v-row>
                <v-row>
                    <v-col cols="6">
                        <v-text-field type="text" label="Tool Name (Required)" v-model="ToolName" ref="ToolName" :error="isError('ToolName')" :error-messages="isErrorMessage('ToolName')"></v-text-field>
                    </v-col>
                    <v-col cols="6">
                        <v-text-field type="text" label="Tool URL (Optional)" v-model="ToolUrl" ref="ToolName" :error="isError('ToolUrl')" :error-messages="isErrorMessage('ToolUrl')"></v-text-field>
                    </v-col>
                </v-row>
                <v-row wrap no-gutters>
                    <v-col cols="5" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                    <v-col cols="2" class="text-center">
                        Roles
                    </v-col>
                    <v-col cols="5" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                </v-row>

                <v-row>
                    <v-col cols="6" v-for="(ToolRole, i) in ToolRoles" :key="i" class="text-fields-row">
                        <v-text-field label="Role" v-model="ToolRole.role" append-icon="" append-icon-color="red" :disabled="ToolRole.assingned != 0">
                            <template v-slot:append>
                                <v-hover v-slot="{ isHovering, props }">       
                                    <v-icon v-if="ToolRole.assingned == 0" v-bind="props" :color="isHovering ? 'red-accent-2' : 'red-accent-4'" @click="remove(i, ToolRole.ID)">mdi-trash-can-outline</v-icon> 
                                </v-hover> 
                            </template>
                        </v-text-field>
                    </v-col>
                </v-row>

                <v-row class="my-0">
                    <v-col cols="6">
                        <v-btn variant="text" @click="add" class="primary" color="green" prepend-icon="mdi-plus">Add Role</v-btn>
                    </v-col>
                </v-row>
                

                <v-row wrap no-gutters>
                    <v-col cols="4" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                    <v-col cols="4" class="text-center">
                        Additional Info
                    </v-col>
                    <v-col cols="4" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                </v-row>

                <v-row>
                    <v-col cols="4" class="py-0">
                        <v-switch v-model="onlineTool" hide-details true-value="Yes" false-value="No" color="green-accent-3">
                            <template #prepend>
                                <p class="mr-1">Online Tool </p>
                                <v-tooltip v-model="onlineToolTooltip" location="top">
                                    <template v-slot:activator="{ props }">
                                        <v-icon v-bind="props" size="small" color="cyan-darken-3" style="cursor: pointer">mdi-chat-question-outline</v-icon>
                                    </template>
                                    <span>Self hosted tool.</span>
                                </v-tooltip>
                            </template>
                        </v-switch>
                    </v-col>
                    <v-col cols="4" class="py-0">
                        <v-switch v-model="toolHas2FA" hide-details true-value="Yes" false-value="No" color="green-accent-3">
                            <template #prepend>
                                <p class="mr-1">Tool has 2FA</p>
                                <v-tooltip v-model="toolHas2FaTooltip" location="top">
                                    <template v-slot:activator="{ props }">
                                        <v-icon v-bind="props" size="small" color="cyan-darken-3" style="cursor: pointer">mdi-chat-question-outline</v-icon>
                                    </template>
                                    <span>Tool requires 2FA auth.</span>
                                </v-tooltip>
                            </template>
                        </v-switch>
                    </v-col>
                    <v-col cols="4" class="py-0">
                        <v-switch v-model="defaultTool" hide-details true-value="Yes" false-value="No" color="green-accent-3">
                            <template #prepend>
                                <p class="mr-1">Default Tool</p>
                                <v-tooltip v-model="defaultToolTooltip" location="top">
                                    <template v-slot:activator="{ props }">
                                        <v-icon v-bind="props" size="small" color="cyan-darken-3" style="cursor: pointer">mdi-chat-question-outline</v-icon>
                                    </template>
                                    <span>Tool will be auto assigned to all new user.</span>
                                </v-tooltip>
                            </template>
                        </v-switch>
                    </v-col>
                </v-row>

            </v-card-text>
            <v-divider class="mt-5"></v-divider>
            <v-card-actions>
                <v-btn color="red darken-1" text @click="closeModal()">
                    Close
                </v-btn>
                <v-spacer></v-spacer>
                <v-btn color="green darken-1" text @click="save()">
                    Save
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog> 
</template>
<script scoped>
    export default {
        expose: ['showDialog'],
        data: () => ({
            editModal: false,
            onlineToolTooltip:false,
            toolHas2FaTooltip:false,
            defaultToolTooltip:false,

            ToolID:'',
            ToolName:"",
            ToolUrl:"",
            onlineTool:"",
            toolHas2FA:"",
            defaultTool:"",
            ToolRoles:[],
            deletedRoles:[],

            errors:{},
            errorsMessages:{},
        }),

        methods: {
            async showDialog(ID, name) {
                this.$root.$refs.overlay.showOverlay(true);
                if (await this.loadDetails(ID) === 'Success') {
                    this.ToolID = ID;
                    this.editModal = true;
                    this.ToolName = name;
                }
                this.$root.$refs.overlay.showOverlay(false);
            },

            closeModal() {
                this.ToolRoles = [];
                this.ToolName = '';
                this.ToolUrl = '';
                this.onlineTool = '';
                this.toolHas2FA = '';
                this.defaultTool = '';
                this.deletedRoles  = [];
                this.errors = {};
                this.errorsMessages = {};
                this.editModal = false;
            },

            add () {
                this.ToolRoles.push({
                    ID: 'new',
                    role: "",
                    assingned:0
                })
            },

            remove (index, ID) {
                this.ToolRoles.splice(index, 1);

                if (ID != 'new') {
                    this.deletedRoles.push({
                        ID: ID,
                    })
                }
            },

            async loadDetails(ID) {
                let response;
                return new Promise((resolve, reject) => {
                    this.$root.axiosGet('/role-manager/tool/info/'+ID).then(data => {
                        response = data.response.data;
                        this.ToolRoles      = response.data.toolRoles;
                        this.ToolName       = response.data.toolName;
                        this.ToolUrl        = response.data.toolUrl;
                        this.onlineTool     = response.data.onlineTool;
                        this.toolHas2FA     = response.data.has2FA;
                        this.defaultTool    = response.data.defaultTool;
                        resolve(response.status);
                    }); 
                });
            },

            isError(fieldName) {
                return this.errors[fieldName];
            },

            isErrorMessage(fieldName) {
                return this.errorsMessages[fieldName];
            },

            save() {
                this.$root.$refs.overlay.showOverlay(true);
                this.errors = {};
                this.errorsMessages = {};
                let response;
                let params = {
                    ToolRoles      : this.ToolRoles,
                    ToolName       : this.ToolName,
                    ToolUrl        : this.ToolUrl,  
                    onlineTool     : this.onlineTool, 
                    toolHas2FA     : this.toolHas2FA, 
                    defaultTool    : this.defaultTool,
                    deletedRoles   : this.deletedRoles 
                };
                console.log(params);
                this.$root.axiosPost('/role-manager/tool/edit/'+this.ToolID, null, params).then(data => {
                    response = data.response.data;
                    this.$root.$refs.overlay.showOverlay(false);
                    if (response.status === 'Error') {
                        if (response.message === 'Validation Error.') {
                            response.data.forEach((el, index) => {
                                Object.entries(el).forEach((el1, index1) => {
                                    this.errors[el1[0]] = !this.isError(el1[0]);
                                    this.errorsMessages[el1[0]] = el1[1];
                                });
                            });
                        }
                    } else {
                        this.closeModal();
                        this.$emit('load-tools');
                    }
                });
            }
        }
    }
</script>