import ngModule from '../../module';
import Section from 'salix/components/section';

export default class Controller extends Section {
    $onInit() {
        this.refresh();
    }

    get path() {
        return `RoleInherits`;
    }

    refresh() {
        let filter = {
            where: {role: this.$params.id},
            include: {
                relation: 'inherits',
                scope: {
                    fields: ['id', 'name', 'description']
                }
            }
        };
        this.$http.get(this.path, {filter})
            .then(res => this.$.data = res.data);
    }

    onAddClick() {
        this.addData = {role: this.$params.id};
        this.$.dialog.show();
    }

    onAddSave() {
        return this.$http.post(this.path, this.addData)
            .then(() => this.refresh())
            .then(() => this.vnApp.showSuccess(this.$t('Role added! Changes will take a while to fully propagate.')));
    }

    onRemove(row) {
        return this.$http.delete(`${this.path}/${row.id}`)
            .then(() => {
                let index = this.$.data.indexOf(row);
                if (index !== -1) this.$.data.splice(index, 1);
                this.vnApp.showSuccess(this.$t('Role removed. Changes will take a while to fully propagate.'));
            });
    }
}

ngModule.component('vnRoleSubroles', {
    template: require('./index.html'),
    controller: Controller
});