import { Modal } from 'ngx-modialog/plugins/bootstrap';
import { UserService } from './../../../shared/user.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { DepartmentService } from './../../../shared/department.service';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';


@Component({
  selector: 'app-department-list',
  templateUrl: './department-list.component.html',
  styleUrls: ['./department-list.component.css']
})
export class DepartmentListComponent implements OnInit {

  constructor(private route: ActivatedRoute,
    private departService: DepartmentService,
    private router: Router,
    private spinner: NgxSpinnerService,
    private modal: Modal,
    private authSer: AuthServiceService,
    private userSer: UserService,
    private toastr: ToastrService) { }

  count: number;
  departmentsList = [];
  departsId = [];
  perPagePagenation: number;
  p: number[] = [];
  currentPage:number = 1;
  filtterStatus = '';
  selectedAll: any;
  pageId: number;
  userLoginId:number;
  serviceId:number;
  dataTableNumber: number = 5;
  pages = [];

  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.route.params.subscribe(
      (params:Params) => {
        console.log(params['departsPageId']);
        this.pageId = params['departsPageId'];
      },
      (error) => {console.log(error)}
    );

    this.route.parent.params.subscribe(
      (params:Params) => {
        this.userLoginId = params['userID'];
        this.serviceId = params['serviceID'];
        this.userSer.getPagesPermetiotns(this.userLoginId, this.serviceId).subscribe(
          (responce) => {
            this.pages = responce['pages'];
            for(let i = 0; i< this.pages.length; i++) {
              if(this.pages[i].name == 'الإدارات') {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_adminstration'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_adminstration'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_adminstration'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }else {
                console.log('no adminstrations');
              }
            }
          },
          (error) => {console.log(error)}
        );
      }
    );

    this.departService.getDeparmentsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.departmentsList = responce['adminstrations'];
        for (var i = 0; i < this.departmentsList.length; i++) {
          this.departmentsList[i].selected = false;
        }
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log(this.departmentsList);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
      }
    );

  };


  //change page 
  onPageChange(pagenationNumber) {
    this.spinner.show();
    this.currentPage = pagenationNumber;
    this.departmentsList = [];
    this.departService.getDeparmentsList(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.departmentsList = responce['adminstrations'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
  };

    //make all checkbox of user checked
    selectAll() {
      for (var i = 0; i < this.departmentsList.length; i++) {
        this.departmentsList[i].selected = this.selectedAll; 
      }
    };
  
    checkIfAllSelected() {
      this.selectedAll = this.departmentsList.every(function(item:any) {
          return item.selected == true;
        });
    };
  

    //filtter function
    filtterFunc(data) {
      this.departmentsList = [];
      console.log(data.target.value);
      const dataSearch = data.target.value;     
      this.currentPage = 1;
      console.log('search curent page', this.currentPage);
      console.log('search page id', this.pageId);
      this.departService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.departmentsList = responce['adminstrations'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log('filtter count', this.count);
          console.log('filtter perPagePAgenation', this.perPagePagenation);
        },
        (error) => {
          console.log(error)
        }
      );
    };

    onGetValue(event) {
      this.spinner.show();
      this.departmentsList = [];
      this.dataTableNumber = event.target.value;
      this.departService.getDeparmentsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.departmentsList = responce['adminstrations'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    };

    //deleted function
    onDeleteDeparts() {
      this.departsId = [];
      for(let i = 0; i < this.departmentsList.length; i++) {
        if(this.departmentsList[i].selected == true) {
          this.departsId.push(this.departmentsList[i].id);
        }
      }

      if(this.departsId.length > 0) {
        const dialogRef = this.modal.alert()
        .size('sm')
        .showClose(true)
        .title('تأكيد الحذف')
        .body(`
            <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
            `)
        .open();
        dialogRef.result
        .then( result =>  
          this.departService.deleteDepart(this.departsId).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم المسح');
              this.spinner.show();
              this.departmentsList = [];
              this.departService.getDeparmentsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
                (responce) => {
                  console.log(responce);
                  this.departmentsList = responce['adminstrations'];
                  for (var i = 0; i < this.departmentsList.length; i++) {
                    this.departmentsList[i].selected = false;
                  }
                  this.count = responce['count'];
                  this.perPagePagenation = responce['per_page'];
                  console.log(this.departmentsList);
                  this.spinner.hide();
                },
                (error) => {
                  console.log(error);
                  this.spinner.hide();
                }
              );
            },
            (error) => {
              console.log(error);
              this.spinner.hide();
            },
          )
        );
      } else{
        this.toastr.warning('لم يتم إختيار أي عنصر للمسح !');
      }
      
    };


    onAddDepart() {
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'addAdminstration']);
    }

    onEdit(departmentIdEit: number) {
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'editAdminstration/edit/' + departmentIdEit]);
    }

    

}
