import { Modal } from 'ngx-modialog/plugins/bootstrap';
import { LectureService } from './../../../shared/lecture.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { UserService } from './../../../shared/user.service';
import { HttpClient } from '@angular/common/http';

import { ActivatedRoute, Router, Params } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';

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

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

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

  ngOnInit() {

    this.spinner.show();

    //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) => {
        this.pageId = params['listPageId'];
        localStorage.setItem('pageIdActive', '15');
      }
    );

    //to show / hide permissions

    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].id == 15) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_lecture'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_lecture'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_lectures'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }else {
                console.log('no lectures');
              }
            }
            this.spinner.hide();
          },
          (error) => {console.log(error)}
        );
      }
    );

    //get list data 
    this.lectureService.getLecturesList(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.lecturesList = responce['lectures'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log('evennnnts', this.lecturesList);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
      }
    );

  }


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

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

  //change page 
  onPageChange(pagenationNumber) {
    this.spinner.show();
    this.currentPage = pagenationNumber;
    this.lecturesList = [];
    //console.log(pagenationNumber);
    //console.log(this.pageId);
    this.lectureService.getLecturesList(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.lecturesList = responce['lectures'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log(this.lecturesList);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
  }
  //filtter function
  filtterFunc(data) {
    this.lecturesList = [];
    const dataSearch = data.target.value;
    console.log(dataSearch);     
    this.currentPage = 1;
    console.log('search curent page', this.currentPage);
    console.log('search page id', this.pageId);
    this.lectureService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.lecturesList = responce['lectures'];
        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)
      }
    );
  };

  changeRanking(event, id) {
    const data = {
      id: id,
      ranking: event.target.value,
    };
    console.log(data);
    this.http.post(this.authSer.pathApi + '/rank_lecture', data).subscribe(
      (responce) => {
        console.log(responce);
        this.lectureService.getLecturesList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
          (responce) => {
            console.log(responce);
            this.count = responce['count'];
            this.perPagePagenation = responce['per_page'];
            this.lecturesList = responce['lectures'];
            console.log(this.lecturesList);
            this.spinner.hide();
          },
          (error) => {
            console.log(error);
          }
        )
      },
      (error) => {console.log(error)},
    );
  };

//determine the list count from select element 
onGetValue(event) {
  this.spinner.show();
  this.lecturesList = [];
  this.dataTableNumber = event.target.value;
  this.lectureService.getLecturesList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
    (responce) => {
      console.log(responce);
      this.lecturesList = responce['lectures'];
      this.count = responce['count'];
      this.perPagePagenation = responce['per_page'];
      this.spinner.hide();
    },
    (error) => {
      console.log(error);
      this.spinner.hide();
    }
  );
}

  onDelete() {
    this.lecturesListIds = [];
    for(let i = 0; i < this.lecturesList.length; i++) {
      if(this.lecturesList[i].selected == true) {
        this.lecturesListIds.push(this.lecturesList[i].id);
      }
    }

    console.log(this.lecturesListIds);

    if(this.lecturesListIds.length > 0) {
      
      const dialogRef = this.modal.alert()
        .size('sm')
        .showClose(true)
        .title('تأكيد الحذف')
        .body(`
            <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
            `)
        .open();
        dialogRef.result
        .then( result =>  
          this.lectureService.deleteLecture(this.lecturesListIds).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم الحذف');
              this.spinner.show();
              this.lecturesList = [];
              this.lectureService.getLecturesList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
                (responce) => {
                  console.log(responce);
                  this.lecturesList = responce['lectures'];
                  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('لم يتم إختيار اي عنصر للحذف !');
    }

  
  };

  //add function
  onAdd() {
    console.log('service/' + this.userLoginId + '/' + this.serviceId + '/addLecture');
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/addLecture']);
  }

  //edit function
   onEdit(editEventID) {
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'Lecture/edit/' + editEventID]);
  }

}
