import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Department } from 'src/app/masters/department/department';
import { DualListComponent } from 'angular-dual-listbox';
import { User } from 'src/app/masters/user/user';
import { Userrolemapping } from './userrolemapping';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Role } from 'src/app/masters/role/role';
import { RoleService } from 'src/app/masters/role/role.service';
import { DepartmentService } from 'src/app/masters/department/department.service';
import { UserService } from 'src/app/masters/user/user.service';
import { UserrolemappingService } from './userrolemapping.service';
import { Router } from '@angular/router';
@Component({
  selector: 'app-userrolemapping',
  templateUrl: './userrolemapping.component.html',
  styleUrls: ['./userrolemapping.component.css']
})
export class UserrolemappingComponent implements OnInit {
  userRoleForm: FormGroup;
  departments: Department[] = [];
  userList: User[] = [];
  selectedUserList: Userrolemapping[] = [];
  orgselectedUserList: Userrolemapping[] = [];

  roles: Role[] = [];
  departmentid: number;
  roleid: number;
  userid: number;
  dropdownSettings = {};
  filter = '';
  formTocuhed = false;
  format = {
    add: 'Add', remove: 'Remove', all: 'All', none: 'None',
    direction: DualListComponent.LTR, draggable: true, filter: true
  };
  actionRights: any;
  constructor(
    private router: Router,
    private formBuilder: FormBuilder,
    private SpinnerService: NgxSpinnerService,
    private toastr: ToastrService,
    private roleService: RoleService,
    private departmentservice: DepartmentService,
    private userservice: UserService,
    private userrolemappingService: UserrolemappingService,
  ) { 
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('UserRoleMapping_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('UserRoleMapping_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('UserRoleMapping_userRights');
    }
  }

  ngOnInit() {
    this.userRoleForm = this.formBuilder.group({
      rolemappingid: [0],
      roleid: [0],
      departmentid: [0],
      userid: [],
      active: [1],
    });

    this.dropdownSettings = {
      singleSelection: false,
      idField: 'userid',
      textField: 'firstname',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 5,
      allowSearchFilter: true
    };
    this.formTocuhed = false;
    this.userid = +localStorage.getItem('userid');
    this.loadDepartments();
    this.loadRoles();
  }

  destinationChange(item: Userrolemapping[]) {
    if (this.departmentid !== 0) {
      this.orgselectedUserList = this.orgselectedUserList.filter(s => s.departmentid !== this.departmentid);
      item.forEach(element => {
        this.orgselectedUserList.push(element);
      });
    } else {
      this.orgselectedUserList = [];
      item.forEach(element => {
        this.orgselectedUserList.push(element);
      });
    }
    this.formTocuhed = true;
  }

  // function to get the existing role details
  loadRoles() {
    this.SpinnerService.show();
    this.roles = [];
    this.roleService.Get().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this.roles = JSON.parse(res[0]);
          this.roles = this.roles.filter(r => r.active === 1);
        }
      }
      this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting data');
    });
  }


 loadDepartments() {
    this.departments = [];
    this.departmentservice.GetActive().subscribe(res => {
      this.departments = JSON.parse(res[0]);
    }, error => { this.toastr.error('Error while getting data'); });
  }

  GetUser() {
    this.SpinnerService.show();
    this.userList = [];
    this.departmentid = +this.userRoleForm.value.departmentid;
    if (this.departmentid === 0) {
      this.userservice.Get().subscribe(res => {
        this.userList = JSON.parse(res[0]);
        if (this.userList) {
          this.userList = this.userList.filter(u => u.active === 1);
        }
        this.SpinnerService.hide();
        this.selectedUserList = this.orgselectedUserList;
      }, error => {
        this.toastr.error('Error while getting users data');
      });
    } else {
      this.userservice.GetUsersByDepartment(this.departmentid).subscribe(res => {
        this.SpinnerService.hide();
        this.userList = JSON.parse(res[0]);
        if (this.userList) {
          this.userList = this.userList.filter(u => u.active === 1);
        }
        if (this.orgselectedUserList.length) {
          this.selectedUserList = this.orgselectedUserList.filter(s => s.departmentid === this.departmentid);
        }
      }, error => {
        this.toastr.error('Error while getting users data');
      });
    }
  }

  GetMappedUserList() {
    this.SpinnerService.show();
    this.roleid = +this.userRoleForm.value.roleid;
    if (this.roleid) {
      this.userrolemappingService.getMappedUserList(this.roleid).subscribe(res => {
        this.GetUser();
        if (res.body[0]) {
          this.SpinnerService.hide();
          this.selectedUserList = JSON.parse(res.body[0]);
          this.orgselectedUserList = JSON.parse(res.body[0]);
          if (this.selectedUserList) {
            if (this.departmentid > 0) {
              this.selectedUserList = this.selectedUserList.filter(s => s.departmentid === this.departmentid);
            }
          }
          this.SpinnerService.hide();
        } else {
          this.SpinnerService.hide();
          this.orgselectedUserList = [];
          this.selectedUserList = [];
          this.SpinnerService.hide();
        }
      }, error => { this.toastr.error('Error while getting data'); });
    } else {
      this.SpinnerService.hide();
      this.orgselectedUserList = [];
      this.selectedUserList = [];
      this.userList = [];
      this.SpinnerService.hide();
    }
  }

  clear() {
    this.userList = [];
    this.orgselectedUserList = [];
    this.selectedUserList = [];
    this.userRoleForm.controls['roleid'].setValue(0);
    this.userRoleForm.controls['departmentid'].setValue(0);
  }

  saveUserRole() {
    this.SpinnerService.show();
    const selectedUserList = this.orgselectedUserList.map(element => ({
      rolemappingid: +(element.rolemappingid) ? +element.rolemappingid : 0,
      roleid: +this.userRoleForm.value.roleid,
      departmentid: +this.userRoleForm.value.departmentid,
      userid: +element.userid,
      active: 1,
      createdby: this.userid,
      updatedby: this.userid
    }));
    if (selectedUserList.length) {
      console.log('selectedUserList=', selectedUserList);
      this.userrolemappingService.Post(selectedUserList).subscribe(res => {
        this.SpinnerService.hide();
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.GetMappedUserList();
              this.toastr.success('Data added successfully');
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          console.log(error);
          this.toastr.error('Error while doing the operation');
        });
    } else {
      this.userRoleForm.value.roleid = +this.userRoleForm.value.roleid;
      this.userrolemappingService.UpdateUserRoleOnEmpty(this.userRoleForm.value).subscribe(res => {
        this.SpinnerService.hide();
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.toastr.success('Data added successfully');
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          console.log(error);
          this.toastr.error('Error while doing the operation');
        });
    }
  }
}
