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

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

  pageId: number;
  count: number;
  userLoginId:number;
  serviceId:number;
  sectionsList = [];
  sectionsId = [];
  pages=[];
  perPagePagenation: number;
  currentPage:number = 1;
  selectedAll: any;
  dataTableNumber: number = 5;

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

  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.internalHeader = false;

    this.route.params.subscribe(
      (params:Params) => {
        this.pageId = params['sectionPageId'];
      }
    );

    this.sectionService.getSectionsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.sectionsList = responce['departments'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        this.spinner.hide();
      },
      (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) => {
            console.log(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_department'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_department'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_department'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }else {
                console.log('no sections');
              }
            }
          },
          (error) => {console.log(error)}
        );
      }
    );

  }

    //change page 
    onPageChange(pagenationNumber) {
      this.spinner.show();
      this.currentPage = pagenationNumber;
      this.sectionsList = [];
      this.sectionService.getSectionsList(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.sectionsList = responce['departments'];
          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.sectionsList.length; i++) {
        this.sectionsList[i].selected = this.selectedAll; 
      }
    };
  
    checkIfAllSelected() {
      this.selectedAll = this.sectionsList.every(function(item:any) {
          return item.selected == true;
        });
    };

    //filtter function
    filtterFunc(data) {
      this.sectionsList = [];
      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.sectionService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.sectionsList = responce['departments'];
          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.sectionsList = [];
      this.dataTableNumber = event.target.value;
      this.sectionService.getSectionsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.sectionsList = responce['departments'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    };

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

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

    onAddSection(){
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'addSection']);
    }
    
    onEdit(idSection:number) {
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'editSection/edit/' + idSection]);
    }
    
  

}
