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

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


  footerId: number;
  footerList = [];
  footerListIds = [];
  count: number;
  perPagePagenation: number;
  p: number[] = [];
  currentPage:number = 1;
  filtterStatus = '';
  selectedAll: any;
  userLoginId:number;
  serviceId:number;
  dataTableNumber: number = 5;
  pages = [];

  serviceName: string = '';


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

  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.footerId = params['listPageId'];
        localStorage.setItem('pageIdActive', params['listPageId']);
      }
    );
    
    //to show / hide permissions

  this.route.parent.params.subscribe(
    (params:Params) => {
        this.userLoginId = params['userID'];
        this.serviceId = params['serviceID'];
        if(this.serviceId == 6) {
          this.serviceName = 'خدمه إداره الصفحه الدخليه';
        } else if(this.serviceId == 2) {
          this.serviceName = 'خدمه إداره الصفحه الخارجيه';
        }
        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 == 16) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_footer'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_footer'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_footers'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              } else if(this.pages[i].id == 29) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_footer_ex'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_footer_ex'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_footers_ex'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }
              else {
                console.log('no events');
              }
            }
            this.spinner.hide();
          },
          (error) => {console.log(error)}
        );
      }
    );

    //get list data 
    this.dashboardService.getListData(this.footerId, this.currentPage ,this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.footerList = responce['footers'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log('evennnnts', this.footerList);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
    
  }

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

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

  //filtter function
  filtterFunc(data) {
    this.footerList = [];
    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.footerId);
    this.dashboardService.getDataUSerSearchBar(dataSearch, this.footerId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.footerList = responce['footers'];
        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)
      }
    );
  };

    //change page 
    onPageChange(pagenationNumber) {
      this.spinner.show();
      this.currentPage = pagenationNumber;
      this.footerList = [];
      //console.log(pagenationNumber);
      //console.log(this.pageId);
      this.dashboardService.getListData(this.footerId, pagenationNumber, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.footerList = responce['footers'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log(this.footerList);
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    }

      //determine the list count from select element 
  onGetValue(event) {
    this.spinner.show();
    this.footerList = [];
    this.dataTableNumber = event.target.value;
    this.dashboardService.getListData(this.footerId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.footerList = responce['footers'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
  };




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

    console.log(this.footerListIds);
    if(this.footerListIds.length > 0) {
      this.footerListIds = [];
      const dialogRef = this.modal.alert()
      .size('sm')
      .showClose(true)
      .title('تأكيد الحذف')
      .body(`
          <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
          `)
      .open();
  
        dialogRef.result
        .then( result => 
          this.dashboardService.deleteItem(this.footerListIds, this.footerId).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم الحذف');
              this.spinner.show();
              this.footerList = [];
              this.dashboardService.getListData(this.footerId, this.currentPage, this.dataTableNumber).subscribe(
                (responce) => {
                  console.log(responce);
                  this.footerList = responce['footers'];
                  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 + '/addFooter');
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/addFooter']);
  }

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

}
