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

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

  externalId: number;
  externalsList = [];
  externalsListIds = [];
  count: number;
  perPagePagenation: number;
  p: number[] = [];
  currentPage:number = 1;
  filtterStatus = '';
  selectedAll: any;
  userLoginId:number;
  serviceId:number;
  dataTableNumber: number = 5;
  pages = [];

  constructor(private route: ActivatedRoute, 
    private router: Router, 
    private userSer: UserService,
    private http: HttpClient,
    private toastr: ToastrService,
    private externalService: ExternalSerService,
    private spinner: NgxSpinnerService,
    private modal: Modal,
    private dashBoardService: DashboardService,
    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.externalId = 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'];
        this.userSer.getPagesPermetiotns(this.userLoginId, this.serviceId).subscribe(
          (responce) => {
            console.log(responce);
            this.pages = responce['pages'];
            if(this.serviceId == 6) {
              for(let i = 0; i< this.pages.length; i++) {
                if(this.pages[i].id == 7) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == 'add_external_service'){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'edit_external_service'){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'delete_external_services'){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                }else {
                  console.log('no events');
                }
              }
            } else if(this.serviceId == 2){
              for(let i = 0; i< this.pages.length; i++) {
                if(this.pages[i].id == 19) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == 'add_external_service_ex'){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'edit_external_service_ex'){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'delete_external_services_ex'){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                }else {
                  console.log('no events');
                }
              }
            }
            this.spinner.hide();
          },
          (error) => {console.log(error)}
        );
      }
    );

    //get list data 
    this.dashBoardService.getListData(this.externalId, this.currentPage ,this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.externalsList = responce['external_services'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log('evennnnts', this.externalsList);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
    
  }

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

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

  //filtter function
  filtterFunc(data) {
    this.externalsList = [];
    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.externalId);
    this.dashBoardService.getDataUSerSearchBar(dataSearch, this.externalId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.externalsList = responce['external_services'];
        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.externalsList = [];
      //console.log(pagenationNumber);
      //console.log(this.pageId);
      this.dashBoardService.getListData(this.externalId, pagenationNumber, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.externalsList = responce['external_services'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log(this.externalsList);
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    }

  changeRanking(event, id) {
    const data = {
      id: id,
      ranking: event.target.value,
    };
    console.log(data);
    this.http.post(this.authSer.pathApi + '/rank_external_service', data).subscribe(
      (responce) => {
        console.log(responce);
        this.externalService.getExternalsList(this.externalId, this.currentPage, this.dataTableNumber).subscribe(
          (responce) => {
            console.log(responce);
            this.count = responce['count'];
            this.perPagePagenation = responce['per_page'];
            this.externalsList = responce['external_services'];
            console.log(this.externalsList);
            this.spinner.hide();
          },
          (error) => {
            console.log(error);
          }
        )
      },
      (error) => {console.log(error)},
    );
  };

  //determine the list count from select element 
  onGetValue(event) {
    this.spinner.show();
    this.externalsList = [];
    this.dataTableNumber = event.target.value;
    this.dashBoardService.getListData(this.externalId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.externalsList = responce['external_services'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
  };
  
  onDelete() {
    this.externalsListIds = [];
    for(let i = 0; i < this.externalsList.length; i++) {
      if(this.externalsList[i].selected == true) {
        this.externalsListIds.push(this.externalsList[i].id);
      }
    }

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

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