import { Component, OnInit } from '@angular/core';
import { XpoDialogRef } from '@xpo/common';
import { Role, RoleService } from '../../shared';

@Component({
    selector: 'app-add-role',
    templateUrl: './add-role.component.html',
    styleUrls: [ './add-role.component.scss' ]
})
export class AddRoleComponent implements OnInit {
    public newRole: Role = undefined;
    private allRoles: Role[];
    private invalidRole: boolean;

    constructor(public dialogRef: XpoDialogRef<AddRoleComponent>, private roleService: RoleService) {
        this.newRole = new Role("", "", true, true);
        this.invalidRole = false;
    }

    ngOnInit() {
        this.roleService.getRoles().then(roles => {
            this.allRoles = roles;
        });
    }

    saveNewRole() {
        if (this.newRole != undefined && this.newRole.name) {
            this.roleService.addRole(this.newRole);
        }
        this.dialogRef.close('canceled');
    }

    validateRole() {
        if (this.newRole != undefined && this.newRole.name) {
            this.invalidRole = false;
            this.allRoles.forEach(role => {
                if (role.name.toLowerCase() == this.newRole.name.toLowerCase()) {
                    this.invalidRole = true;
                }
            })
        }

    }

    onClose() {
        this.dialogRef.close('canceled');
    }
}
