<template>
    <v-card
        tile
        flat
        :loading="dataprovider.processing"
        :disabled="dataprovider.processing"
    >
        <div class="font-weight-bold" v-if="!! label">
            {{ __(label) }}
        </div>

        <v-sheet
            :height="height"
            :class="{
                'overflow-y-auto': !! height,
            }"
        >
            <v-treeview
                dense
                selectable
                open-all
                :disabled="disabled"
                selection-type="leaf"
                :items="items"
                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-sheet>
    </v-card>
</template>

<script>
    import PermissionsDataProvider from 'APPS/Dataproviders/Permissions/Permissions';

    export default {

        props: {
            value: {default: () => []},
            disabled: {default: false},
            height: {default: 480},
            slugs: {default: () => []},
            label: {default: ''},
            app: {required: true},
        },

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

        computed: {
            selected: {
                get: function() {
                    return this.dataprovider.ToPermisionsIds(this.value);
                },

                set: function(permissions_ids) {
                    this.$emit('input', this.dataprovider.ToHuman(permissions_ids));
                }
            },

            items() {
                return this.dataprovider.items;
            }
        },

        methods: {
            OpenAllNodes() {
                let i = setInterval( () => {
                    if( ! this.dataprovider.processing )
                    {
                        clearInterval(i);
                        this.$refs.PermisionsTree.updateAll(true);
                        this.selected = this.dataprovider.ToPermisionsIds(this.value);
                    }
                }, 400)
            }
        },

        created() {
            this.dataprovider = new PermissionsDataProvider(this.app);
            this.dataprovider.GetBySlugs(this.slugs);
            this.OpenAllNodes();
        },

        name: 'UserPermissionsTree',
    }
</script>