import { Component, Input } from '@angular/core';
import { Role } from '../role.model';
import { debounceTime, distinctUntilChanged } from 'rxjs';
import * as i0 from "@angular/core";
import * as i1 from "../../core";
import * as i2 from "@angular/router";
import * as i3 from "../../user-config";
import * as i4 from "@angular/forms";
import * as i5 from "@angular/common";
import * as i6 from "@angular/flex-layout/flex";
import * as i7 from "@angular/material/button";
import * as i8 from "@angular/material/form-field";
import * as i9 from "@angular/material/icon";
import * as i10 from "@angular/material/input";
import * as i11 from "@angular/material/core";
import * as i12 from "@angular/material/select";
import * as i13 from "@angular/material/card";
/**
 * Role Permissions management controller
 *
 * @author Joshua Kissoon
 * @since 20161013
 */
export class PermissionsManagementComponent {
    constructor(http, alertService, route, credentialsService, errorHandler, userConfigService, fb) {
        this.http = http;
        this.alertService = alertService;
        this.route = route;
        this.credentialsService = credentialsService;
        this.errorHandler = errorHandler;
        this.userConfigService = userConfigService;
        this.fb = fb;
        this.moduleCode = null;
        this.config = this.userConfigService.getConfig();
        this.filterForm = this.fb.group({
            search: [''],
            role_ids: []
        });
    }
    setFilteredPermissions() {
        if (this.filterForm.get('search').value) {
            this.filteredPermissions = this.permissions
                .filter((permission) => permission.label.toLocaleLowerCase()
                .includes(this.filterForm.get('search').value.toString().toLocaleLowerCase()));
        }
        else {
            this.filteredPermissions = this.permissions;
        }
    }
    ngOnInit() {
        this.filterForm.get('search').valueChanges.pipe(debounceTime(500), distinctUntilChanged()).subscribe(_ => this.setFilteredPermissions());
        this.route.params.subscribe(params => {
            if (params.module_code !== undefined) {
                this.moduleCode = params.module_code;
            }
            this.loadRoles();
            this.loadPermissions();
        });
    }
    isDisabled(isGlobal, isEditable) {
        if (isGlobal && this.credentialsService.credentials?.user?.user_type_id !== 1) {
            return !isEditable;
        }
        return false;
    }
    loadPermissions() {
        const filters = {};
        if (this.moduleCode) {
            filters.module_code = this.moduleCode;
        }
        if (this.clientId) {
            filters.client_id = this.clientId;
        }
        this.http.get('api/permissions', { params: filters }).toPromise().then((res) => {
            this.permissions = res.data;
            this.setFilteredPermissions();
        });
    }
    /**
     * Load the Roles from the DB
     */
    loadRoles() {
        const filters = {
            loadPermissions: true,
        };
        if (this.clientId) {
            filters.client_id = this.clientId;
        }
        this.http.get('api/roles', { params: filters }).toPromise().then((res) => {
            this.roles = new Array();
            for (let row of res.data) {
                let role = new Role();
                role.loadFromJson(row);
                this.roles.push(role);
                role.setupBlankPermissionsForNgModel();
            }
            this.filterForm.get('role_ids').setValue(this.roles.map(role => role.id));
        }, error => {
            this.errorHandler.handleError(error);
        });
    }
    updateRolePermission(role, permission) {
        let data = {
            rid: role.id,
            permission: permission.slug
        };
        if (role.hasPermission(permission.slug)) {
            /* Remove the permission  */
            this.http.patch('api/roles/' + role.id + '/permissions/' + permission.id + '/remove', data).toPromise().then(res => {
                role.removePermission(permission);
                this.alertService.addAlert(permission.label + ' removed', 'warning');
            });
        }
        else {
            /* Add the permission */
            this.http.patch('api/roles/' + role.id + '/permissions/' + permission.id + '/add', data).toPromise().then(res => {
                role.addPermission(permission);
                this.alertService.addAlert(permission.label + ' added', 'success');
            });
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: PermissionsManagementComponent, deps: [{ token: i1.HttpService }, { token: i1.AlertService }, { token: i2.ActivatedRoute }, { token: i1.CredentialsService }, { token: i1.ErrorHandlerService }, { token: i3.UserConfigService }, { token: i4.FormBuilder }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.13", type: PermissionsManagementComponent, selector: "role-permissions-management", inputs: { clientId: "clientId" }, ngImport: i0, template: "<div fxLayout=\"column\" class=\"m-2\">\n\n    <mat-card appearance=\"outlined\" fxLayoutAlign=\"start center\">\n        <h5 class=\"m-0\">\n            Manage Role Permissions\n        </h5>\n        <button mat-raised-button [routerLink]=\"['../users']\" *ngIf=\"!config.permissionConfig.disableUsers\"\n            class=\"ml-1\">\n            <i class=\"icon fas fa-users\"></i> Users\n        </button>\n        <button mat-raised-button [routerLink]=\"['../roles']\" *ngIf=\"!config.permissionConfig.disableRoles\"\n            class=\"ml-1\">\n            <i class=\"fas fa-user-md\"></i> Manage Roles\n        </button>\n        <span fxFlex></span>\n        <form [formGroup]=\"filterForm\">\n\n            <mat-form-field appearance=\"outline\">\n                <mat-label>Search</mat-label>\n                <input type=\"text\" matInput formControlName=\"search\" placeholder=\"Search Permissions\"\n                    autocomplete=\"off\" />\n                <button mat-icon-button matSuffix type=\"button\" *ngIf=\"filterForm.get('search').value\"\n                    (click)=\"filterForm.get('search').setValue('')\">\n                    <mat-icon>clear</mat-icon>\n                </button>\n            </mat-form-field>\n\n            <mat-form-field *ngIf=\"roles\" appearance=\"outline\" class=\"ml-2\">\n                <mat-label>Show Roles</mat-label>\n                <mat-select formControlName='role_ids' multiple>\n                    <mat-option *ngFor=\"let role of roles\" [value]=\"role?.id\">\n                        {{role.label}}\n                    </mat-option>\n                </mat-select>\n            </mat-form-field>\n        </form>\n    </mat-card>\n\n    <mat-card appearance=\"outlined\" class=\"p-0 mt-2\">\n        <form>\n            <table class=\"table table-sm table-bordered table-condensed table-striped\"\n                aria-describedby=\"Role Permissions\">\n                <thead>\n                    <tr>\n                        <th>Permissions</th>\n                        <ng-container *ngFor=\"let role of roles\">\n                            <th class=\"text-center\" *ngIf=\"filterForm.get('role_ids').value.includes(role.id)\">\n                                {{role.label}}\n                            </th>\n                        </ng-container>\n                    </tr>\n                </thead>\n                <tbody>\n                    <tr *ngFor=\"let permission of filteredPermissions\">\n                        <td>\n                            {{permission.label}}</td>\n                        <ng-container *ngFor=\"let role of roles\">\n                            <td class=\"text-center\" *ngIf=\"filterForm.get('role_ids').value.includes(role.id)\">\n                                <input [disabled]=\"isDisabled(role.is_global, role.is_editable)\" type=\"checkbox\"\n                                    name=\"{{role.id}}[{{permission?.label}}]\"\n                                    [checked]=\"role.hasPermission(permission.slug)\"\n                                    (change)=\"updateRolePermission(role, permission)\" />\n                            </td>\n                        </ng-container>\n                    </tr>\n                </tbody>\n            </table>\n        </form>\n    </mat-card>\n</div>", dependencies: [{ kind: "directive", type: i5.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i5.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i2.RouterLink, selector: "[routerLink]", inputs: ["target", "queryParams", "fragment", "queryParamsHandling", "state", "info", "relativeTo", "preserveFragment", "skipLocationChange", "replaceUrl", "routerLink"] }, { kind: "directive", type: i6.DefaultLayoutDirective, selector: "  [fxLayout], [fxLayout.xs], [fxLayout.sm], [fxLayout.md],  [fxLayout.lg], [fxLayout.xl], [fxLayout.lt-sm], [fxLayout.lt-md],  [fxLayout.lt-lg], [fxLayout.lt-xl], [fxLayout.gt-xs], [fxLayout.gt-sm],  [fxLayout.gt-md], [fxLayout.gt-lg]", inputs: ["fxLayout", "fxLayout.xs", "fxLayout.sm", "fxLayout.md", "fxLayout.lg", "fxLayout.xl", "fxLayout.lt-sm", "fxLayout.lt-md", "fxLayout.lt-lg", "fxLayout.lt-xl", "fxLayout.gt-xs", "fxLayout.gt-sm", "fxLayout.gt-md", "fxLayout.gt-lg"] }, { kind: "directive", type: i6.DefaultLayoutAlignDirective, selector: "  [fxLayoutAlign], [fxLayoutAlign.xs], [fxLayoutAlign.sm], [fxLayoutAlign.md],  [fxLayoutAlign.lg], [fxLayoutAlign.xl], [fxLayoutAlign.lt-sm], [fxLayoutAlign.lt-md],  [fxLayoutAlign.lt-lg], [fxLayoutAlign.lt-xl], [fxLayoutAlign.gt-xs], [fxLayoutAlign.gt-sm],  [fxLayoutAlign.gt-md], [fxLayoutAlign.gt-lg]", inputs: ["fxLayoutAlign", "fxLayoutAlign.xs", "fxLayoutAlign.sm", "fxLayoutAlign.md", "fxLayoutAlign.lg", "fxLayoutAlign.xl", "fxLayoutAlign.lt-sm", "fxLayoutAlign.lt-md", "fxLayoutAlign.lt-lg", "fxLayoutAlign.lt-xl", "fxLayoutAlign.gt-xs", "fxLayoutAlign.gt-sm", "fxLayoutAlign.gt-md", "fxLayoutAlign.gt-lg"] }, { kind: "directive", type: i6.DefaultFlexDirective, selector: "  [fxFlex], [fxFlex.xs], [fxFlex.sm], [fxFlex.md],  [fxFlex.lg], [fxFlex.xl], [fxFlex.lt-sm], [fxFlex.lt-md],  [fxFlex.lt-lg], [fxFlex.lt-xl], [fxFlex.gt-xs], [fxFlex.gt-sm],  [fxFlex.gt-md], [fxFlex.gt-lg]", inputs: ["fxFlex", "fxFlex.xs", "fxFlex.sm", "fxFlex.md", "fxFlex.lg", "fxFlex.xl", "fxFlex.lt-sm", "fxFlex.lt-md", "fxFlex.lt-lg", "fxFlex.lt-xl", "fxFlex.gt-xs", "fxFlex.gt-sm", "fxFlex.gt-md", "fxFlex.gt-lg"] }, { kind: "component", type: i7.MatButton, selector: "    button[mat-button], button[mat-raised-button], button[mat-flat-button],    button[mat-stroked-button]  ", exportAs: ["matButton"] }, { kind: "component", type: i7.MatIconButton, selector: "button[mat-icon-button]", exportAs: ["matButton"] }, { kind: "component", type: i8.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i8.MatLabel, selector: "mat-label" }, { kind: "directive", type: i8.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "component", type: i9.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "directive", type: i10.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl],      input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly"], exportAs: ["matInput"] }, { kind: "component", type: i11.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "component", type: i12.MatSelect, selector: "mat-select", inputs: ["aria-describedby", "panelClass", "disabled", "disableRipple", "tabIndex", "hideSingleSelectionIndicator", "placeholder", "required", "multiple", "disableOptionCentering", "compareWith", "value", "aria-label", "aria-labelledby", "errorStateMatcher", "typeaheadDebounceInterval", "sortComparator", "id", "panelWidth"], outputs: ["openedChange", "opened", "closed", "selectionChange", "valueChange"], exportAs: ["matSelect"] }, { kind: "component", type: i13.MatCard, selector: "mat-card", inputs: ["appearance"], exportAs: ["matCard"] }, { kind: "directive", type: i4.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i4.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i4.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i4.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i4.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i4.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i4.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: PermissionsManagementComponent, decorators: [{
            type: Component,
            args: [{ selector: 'role-permissions-management', template: "<div fxLayout=\"column\" class=\"m-2\">\n\n    <mat-card appearance=\"outlined\" fxLayoutAlign=\"start center\">\n        <h5 class=\"m-0\">\n            Manage Role Permissions\n        </h5>\n        <button mat-raised-button [routerLink]=\"['../users']\" *ngIf=\"!config.permissionConfig.disableUsers\"\n            class=\"ml-1\">\n            <i class=\"icon fas fa-users\"></i> Users\n        </button>\n        <button mat-raised-button [routerLink]=\"['../roles']\" *ngIf=\"!config.permissionConfig.disableRoles\"\n            class=\"ml-1\">\n            <i class=\"fas fa-user-md\"></i> Manage Roles\n        </button>\n        <span fxFlex></span>\n        <form [formGroup]=\"filterForm\">\n\n            <mat-form-field appearance=\"outline\">\n                <mat-label>Search</mat-label>\n                <input type=\"text\" matInput formControlName=\"search\" placeholder=\"Search Permissions\"\n                    autocomplete=\"off\" />\n                <button mat-icon-button matSuffix type=\"button\" *ngIf=\"filterForm.get('search').value\"\n                    (click)=\"filterForm.get('search').setValue('')\">\n                    <mat-icon>clear</mat-icon>\n                </button>\n            </mat-form-field>\n\n            <mat-form-field *ngIf=\"roles\" appearance=\"outline\" class=\"ml-2\">\n                <mat-label>Show Roles</mat-label>\n                <mat-select formControlName='role_ids' multiple>\n                    <mat-option *ngFor=\"let role of roles\" [value]=\"role?.id\">\n                        {{role.label}}\n                    </mat-option>\n                </mat-select>\n            </mat-form-field>\n        </form>\n    </mat-card>\n\n    <mat-card appearance=\"outlined\" class=\"p-0 mt-2\">\n        <form>\n            <table class=\"table table-sm table-bordered table-condensed table-striped\"\n                aria-describedby=\"Role Permissions\">\n                <thead>\n                    <tr>\n                        <th>Permissions</th>\n                        <ng-container *ngFor=\"let role of roles\">\n                            <th class=\"text-center\" *ngIf=\"filterForm.get('role_ids').value.includes(role.id)\">\n                                {{role.label}}\n                            </th>\n                        </ng-container>\n                    </tr>\n                </thead>\n                <tbody>\n                    <tr *ngFor=\"let permission of filteredPermissions\">\n                        <td>\n                            {{permission.label}}</td>\n                        <ng-container *ngFor=\"let role of roles\">\n                            <td class=\"text-center\" *ngIf=\"filterForm.get('role_ids').value.includes(role.id)\">\n                                <input [disabled]=\"isDisabled(role.is_global, role.is_editable)\" type=\"checkbox\"\n                                    name=\"{{role.id}}[{{permission?.label}}]\"\n                                    [checked]=\"role.hasPermission(permission.slug)\"\n                                    (change)=\"updateRolePermission(role, permission)\" />\n                            </td>\n                        </ng-container>\n                    </tr>\n                </tbody>\n            </table>\n        </form>\n    </mat-card>\n</div>" }]
        }], ctorParameters: () => [{ type: i1.HttpService }, { type: i1.AlertService }, { type: i2.ActivatedRoute }, { type: i1.CredentialsService }, { type: i1.ErrorHandlerService }, { type: i3.UserConfigService }, { type: i4.FormBuilder }], propDecorators: { clientId: [{
                type: Input
            }] } });
//# sourceMappingURL=data:application/json;base64, 