<template>
    <v-card
        tile
        flat
        :height="height"
        :disabled="isDisabled"
        :loading="loading"
        class="overflow-y-auto"
    >
        <v-treeview
            dense
            selectable
            open-all
            :disabled="false"
            selection-type="leaf"
            :items="existsPermissions"
            ref="PermisionsTree"
            v-model="selected"
        >
            <template #label="{item}">
                <div class="text-caption d-flex align-center justify-space-between mb-1">
                    <v-sheet>
                        {{item.name}} 
                    </v-sheet>
                </div>
            </template>
        </v-treeview>
    </v-card>
</template>

<script>

    import PermissionsDataprovider from 'APPS/Dataproviders/Permissions/Permissions';

    export default {
        props: {
            height: {default: null},
            app: {required: true},
            user: {required: true},
        },

        data: () => ({
            permissionsManager: {
                dataprovider: null,
            },

            selected: [],

            t: null,
        }),

        computed: {
            existsPermissions() {
                return this.permissionsManager.dataprovider.items;
            },

            permissions() {
                return {
                    ...this.user.role.permissions,
                    ...this.user.permissions,
                };
            },

            isDisabled() {
                return this.permissionsManager.dataprovider.loading;
            },

            loading() {
                return this.permissionsManager.dataprovider.loading;
            }
        },

        watch: {
            selected: function() {
                if(this.t)
                {
                    clearTimeout(this.t);
                }

                this.t = setTimeout( () => {
                    this.app.requests.Userupdatepermissions.ResetData().SetData({
                        user_id: this.user.id,
                        permissions: this.permissionsManager.dataprovider.ToHuman(this.selected),
                    }).Request([
                        response => {
                        }
                    ])

                }, 500);
            }
        },

        created() {
            this.permissionsManager.dataprovider = new PermissionsDataprovider(this.app);
            this.permissionsManager.dataprovider.GetRootPermissions();

            let i = setInterval(() => {

                if(! this.permissionsManager.dataprovider.processing )
                {
                    clearInterval(i);
                    this.$refs.PermisionsTree.updateAll(true);
                    this.selected = this.permissionsManager.dataprovider.ToPermisionsIds(this.permissions);
                }
            }, 350)

           

            
        },

        name: 'UserPermissionsSettings',
    }
</script>