import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { XpoDialog, XpoDialogConfig, XpoDialogRef, BreadCrumbService } from '@xpo/common';
import { Role, RoleService, Application, ApplicationService } from '../../shared';
import { AddRoleComponent } from '../add-role/add-role.component';
import { DeleteRoleConfirmationComponent } from '../delete-role-confirmation/delete-role-confirmation.component';

@Component({
    selector: 'app-roles-list',
    templateUrl: './roles-list.component.html',
    styleUrls: [ './roles-list.component.scss' ]
})

export class RolesListComponent implements OnInit {
    private dialogConfig: XpoDialogConfig;
    private allRoles: Role[];
    private rolesListLength: number;
    private allApplications: Application[];
    private applicationListLength: number;

    constructor(private dialog: XpoDialog, private roleService: RoleService, private applicationService: ApplicationService, private bcService: BreadCrumbService) {
        this.dialogConfig = new XpoDialogConfig();
        this.dialogConfig.width = '500';
    }

    ngOnInit() {
        this.applicationService.getApplications().then(application => {
            this.allApplications = application;
            this.applicationListLength = this.allApplications.length;
        });

        this.roleService.getRoles().then(roles => {
            this.allRoles = roles;
            this.rolesListLength = this.allRoles.length;
            this.bcService.setCrumbs({ breadcrumb: [ { name: 'count roles', link: './' }] });
        });
    }

    addRole() {
        this.dialog
            .open(AddRoleComponent, this.dialogConfig)
            .afterClosed()
            .subscribe((result) => {
                this.ngOnInit;
                this.rolesListLength = this.allRoles.length;
            });
    }

    deleteRole(selectedRole: Role) {
        this.dialogConfig.data = selectedRole;
        this.dialog
            .open(DeleteRoleConfirmationComponent, this.dialogConfig)
            .afterClosed()
            .subscribe((result) => {
                this.ngOnInit;
                this.rolesListLength = this.allRoles.length;
            });
    }
}
