import { Component, OnInit } from '@angular/core';
import { Department } from 'src/app/masters/department/department';
import { DepartmentService } from 'src/app/masters/department/department.service';
import { ToastrService } from 'ngx-toastr';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
import { ProjectConfigurationService } from 'src/app/projectconfiguration/projectconfiguration/projectconfiguration.service';
import { User } from 'src/app/masters/user/user';
import { UserService } from 'src/app/masters/user/user.service';
import { Userprojectmapping } from './userprojectmapping';
import { UserprojectmappingService } from './userprojectmapping.service';
import { DualListComponent } from 'angular-dual-listbox';
import { NgxSpinnerService } from 'ngx-spinner';
import { Router } from '@angular/router';
@Component({
  selector: 'app-userprojectmapping',
  templateUrl: './userprojectmapping.component.html',
  styleUrls: ['./userprojectmapping.component.css']
})
export class UserprojectmappingComponent implements OnInit {
  projectDefinitions: any[] = [];
  departments: Department[] = [];
  userProjectForm: FormGroup;
  userList: User[] = [];
  dropdownList = [];
  selectedItems = [];
  dropdownSettings = {};
  selectedUserList: Userprojectmapping[] = [];
  orgselectedUserList: Userprojectmapping[] = [];
  userprojectmapping: Userprojectmapping[];
  userid: number;
  departmentid: number;
  project_definitionid: number;
  filter = true;
  actionRights: any;
  constructor(
    private router: Router,
    private formBuilder: FormBuilder,
    private departmentservice: DepartmentService,
    private toastr: ToastrService,
    private projectConfigurationService: ProjectConfigurationService,
    private userservice: UserService,
    private userprojectmappingService: UserprojectmappingService,
    private SpinnerService: NgxSpinnerService,
  ) {  // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('UserProjectMapping_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('UserProjectMapping_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('UserProjectMapping_userRights');
    }}
  formTocuhed = false;
  format = {
    add: 'Add', remove: 'Remove', all: 'All', none: 'None',
    direction: DualListComponent.LTR, draggable: true, filter: true
  };
  ngOnInit() {
    this.userProjectForm = this.formBuilder.group({
      projectmappingid: [0],
      project_definitionid: [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.loadProjectDefinitions();
  }
  destinationChange(item: Userprojectmapping[]) {
    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;
  }
  loadProjectDefinitions() {
    this.projectDefinitions = [];
    this.projectConfigurationService.GetActiveProjectDefinition().subscribe(res => {
      this.projectDefinitions = JSON.parse(res[0]);
      this.projectDefinitions = this.projectDefinitions.filter(d => d.active === 1);
    }, error => { 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'); });
  }
  // Choose city using select dropdown

  GetUser() {
    this.SpinnerService.show();
    this.userList = [];
    this.departmentid = +this.userProjectForm.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.userList = JSON.parse(res[0]);
        if(this.userList) {
          this.userList = this.userList.filter(u => u.active === 1);
          }
        this.SpinnerService.hide();
        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.project_definitionid = +this.userProjectForm.value.project_definitionid;
    if (this.project_definitionid) {
      this.userprojectmappingService.getMappedUserList(this.project_definitionid).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.userProjectForm.controls['project_definitionid'].setValue(0);
    this.userProjectForm.controls['departmentid'].setValue(0);
  }

  MapUserProject() {
    this.SpinnerService.show();
    const selectedUserList = this.orgselectedUserList.map(element => ({
      projectmappingid: +(element.projectmappingid) ? +element.projectmappingid : 0,
      project_definitionid: +this.userProjectForm.value.project_definitionid,
      departmentid: +this.userProjectForm.value.departmentid,
      userid: +element.userid,
      active: 1,
      createdby: this.userid,
      updatedby: this.userid
    }));
    if (selectedUserList.length) {
      console.log('selectedUserList=', selectedUserList);
      this.userprojectmappingService.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.userProjectForm.value.project_definitionid = +this.userProjectForm.value.project_definitionid;
      this.userprojectmappingService.UpdateUserProjectOnEmpty(this.userProjectForm.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');
        });
    }
  }
}

