import { Component, OnInit } from '@angular/core';
import { User, UserService, DivisionRole, DivisionService } from '../../shared';

@Component({
  selector: 'app-division-role',
  templateUrl: './division-role.component.html',
  styleUrls: [ './division-role.component.scss' ],
  providers: [ DivisionService ]
})
export class DivisionRoleComponent implements OnInit {

  selectedUser: User;
  divisionNames = [];
  divisions: DivisionRole[];
  numberOfDivisions: number;
  roles: any[] = [];
  private addDivisionRoleButton;

  constructor(private divisionService: DivisionService, private userService: UserService) {
    this.divisionService.getDivisionList().then(divisionRole => {
      this.divisions = divisionRole;
      this.numberOfDivisions = this.divisions.length;
    });
    this.userService.getEditUserInfo().then(user => {
      this.selectedUser = user;
      if (this.selectedUser.id != null) {
        this.addDivisionRoleButton = true;
      }
      for (let i = 0; i < this.selectedUser.roles.length; i++) {
        this.divisionNames.push(this.selectedUser.roles[ i ]);
        this.divisionService.getRolesWithDivision(this.selectedUser.roles[ i ].divisionName).then(role => { this.roles[ i ] = role });
      }
    });
  }

  ngOnInit() {
    var selectedDivNames = [];
    var divNames = [];
    this.divisionNames.forEach(element => {
      selectedDivNames.push(element.divisionName);
    });
    this.divisions.forEach(element => {
      if (selectedDivNames.indexOf(element.divisionName) == -1) {
        divNames.push(element);
      }
    })
    this.divisions = divNames;
  }

  onSelect(index) {
    this.divisionService.getRolesWithDivision(this.divisionNames[ index ].divisionName).then(role => { this.roles[ index ] = role });
    this.selectedUser.roles[ index ] = this.divisionNames[ index ];
    let j = this.divisions.findIndex(role => role.divisionName == this.divisionNames[ index ].divisionName);
    this.divisions.splice(j, 1);
  }

  onSelectRole(index) {
    this.selectedUser.roles[ index ].roleName = this.divisionNames[ index ].roleName;
    this.addDivisionRoleButton = true;
  }

  addDivisionRole() {
    if (this.addDivisionRoleButton) {
      this.selectedUser.roles.push(new DivisionRole(1, 1, "", ""));
      this.divisionNames.push(new DivisionRole(1, 1, "", ""));
    }
    this.addDivisionRoleButton = false;
  }

  onDeleteDivisionRole(index) {
    this.divisions.push(this.divisionNames[ index ]);
    this.selectedUser.roles.splice(index, 1);
    this.divisionNames.splice(index, 1);
    this.roles.splice(index, 1);
  }

}
