import { Subscription } from 'rxjs';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { DashboardService } from './../../../shared/dashboard.service';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Modal } from 'ngx-modialog/plugins/bootstrap';
import { UserService } from '../../../shared/user.service';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-adminstration-contact-officers-list',
  templateUrl: './adminstration-contact-officers-list.component.html',
  styleUrls: ['./adminstration-contact-officers-list.component.css']
})
export class AdminstrationContactOfficersListComponent implements OnInit, OnDestroy {

  constructor(private http: HttpClient,
    private route: ActivatedRoute,
    private router: Router,
    private modal: Modal,
    private userSer: UserService,
    private spinner: NgxSpinnerService,
    private authSer: AuthServiceService,
    private toastr: ToastrService,
    private dashboardSer: DashboardService) { }

    currentadmins = [];
    emplyees =[];
    pages= [];
    pageId: number;
    Ids = [];
    count: number;
    perPagePagenation: number;
    currentPage:number = 1;
    filtterStatus = 'all';
    selectedAll: any;
    userLoginId:number;
    serviceId:number;
    dataTableNumber: number = 5;
    absorpationListIds = [];
    dataListIds = [];
    onSaving: boolean = false;
    selected: boolean = false;
    checkSaveDisabled:boolean = false;

    subscriptionVar: Subscription;

  ngOnInit() {
  //init the values of permision boolean
  this.authSer.showAddBtn = false;
  this.authSer.showDeleteBtn = false;
  this.authSer.showEditBtn = false;
  //show / hide notification search in header
  this.authSer.notificationLogin = true;
  this.authSer.showSearchHeader = false;
  this.authSer.showHeaderLogin = false;
  this.authSer.showHeaderDashBoard = true;
  this.authSer.showDashboardHeader = true;
  this.authSer.internalHeader = false;
  
    this.spinner.show();

   this.subscriptionVar = this.route.params.subscribe(
      (params) =>{
      this.pageId = params['adminId'];
      localStorage.setItem('pageIdActive', params['adminId']);

      if(this.pageId == 54){
        this.http.get(this.authSer.pathApi + '/current_employees_officer_for_adminstration').subscribe(
 
      (response) => {
       this.currentadmins = response['officers'];
       this.spinner.hide();
      },
      (error) => {
       console.log(error);
      
      }
      
      );
      this.http.get(this.authSer.pathApi+ '/get_adminstration_employees').subscribe(
       (response) => {
         console.log(response);
         this.emplyees = response['users'];
         this.selectCurrentAdmin();
       },
       (error) => {
         console.log(error);
       }
      );


     } else if(this.pageId == 57){
       this.http.get(this.authSer.pathApi + '/current_employees_officer_for_department').subscribe(
    
         (response) => {
          this.currentadmins = response['officers'];
          this.spinner.hide();
         },
         (error) => {
          console.log(error);
         }
         
         );
         this.http.get(this.authSer.pathApi+ '/get_department_employees').subscribe(
          (response) => {
            console.log(response);
            this.emplyees = response['users'];
            this.selectCurrentAdmin();
          },
          (error) => {
            console.log(error);
          }
         );
        }
      }
    );
     
  }

//make all checkbox of user checked 
selectAll() {
  for (var i = 0; i < this.emplyees.length; i++) {
    this.emplyees[i].selected = this.selectedAll;
    }
  }

  checkIfAllSelected() {
    this.selectedAll = this.emplyees.every(function(item:any) {
        return item.selected == true;
      })
  }

  ngOnDestroy() {
    this.subscriptionVar.unsubscribe();
  }
  
  //checkCurrentAdminFunction

  selectCurrentAdmin() {
    for (let i = 0; i< this.currentadmins.length; i++) {
      for(let j = 0; j < this.emplyees.length; j++) {
        if(this.currentadmins[i].id == this.emplyees[j].id){
          this.emplyees[i].selected = true;
        }
      }
     }
  }

  onSubmit() {

    const employeesIds = [];
    this.checkSaveDisabled = true;


    for(let i = 0 ; i < this.emplyees.length; i++) {
      if(this.emplyees[i].selected == true) {
        employeesIds.push(this.emplyees[i].id);
      };
    }
    if(employeesIds.length == 0){
      this.toastr.success('تم نعين ضباط الاتصال');
      this.checkSaveDisabled = false;
    }else{
      if(this.pageId == 54){
      this.http.post(this.authSer.pathApi + '/asign_adminstration_employees_to_contact_officers', {'officers' : employeesIds}).subscribe(
        (response) => {
          this.currentadmins = [];
          for(let i = 0 ; i < this.emplyees.length; i++) {  
            if(this.emplyees[i].selected == true) {
              this.currentadmins.push(this.emplyees[i]);
            };  
          }
          this.toastr.success('تم نعين ضباط الاتصال');
          location.reload();
          console.log(response);
          for(let i = 0; i < this.emplyees.length; i++){
            this.emplyees[i].selected == false;
          }
        },
        (error) => {
          this.toastr.error('حدث خطئ في التعين يرجا المحاوله لاحقاً')
          console.log(error);
        }
      );
    }
      else  if(this.pageId == 57){
      this.http.post(this.authSer.pathApi + '/asign_department_employees_to_contact_officers',{'officers' : employeesIds} ).subscribe(
        (response) => {
          this.currentadmins = [];
          for(let i = 0 ; i < this.emplyees.length; i++) {  
            if(this.emplyees[i].selected == true) {
                this.currentadmins.push(this.emplyees[i]);
                };  
          }
          this.toastr.success('تم نعين ضباط الاتصال');
          console.log(response);
          location.reload();
        },
        (error) => {
          this.toastr.error('حدث خطأ في التعين يرجا المحاوله لاحقاً')
          console.log(error);
        }
      );
    }
      this.checkSaveDisabled = false;
    }
  }
}
