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

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

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

  pageId: number;


  pages= [];
  trainnersData = [];
  trainnersListIds = [];
  count: number;
  perPagePagenation: number;
  currentPage:number = 1;
  filtterStatus = '';
  selectedAll: any;
  userId:number;
  serviceId:number;
  dataTableNumber: number = 5;

  ngOnInit() {

    this.spinner.show();
    //init values of permisions
    this.authSer.showAddBtn = false;
    this.authSer.showDeleteBtn = false;
    this.authSer.showEditBtn = false;
    this.authSer.showPermissionsBtn = 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;
    //to show / hide permissions

    this.route.parent.params.subscribe(
      (params:Params) => {
          this.userId = params['userID'];
          this.serviceId = params['serviceID'];
          this.userSer.getPagesPermetiotns(this.userId, 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 == 40) {
                  if(this.pages[i]['permissions'][0].name == 'trainees') {
                    this.authSer.showAddBtn = true;
                    this.authSer.showEditBtn = true;
                    this.authSer.showDeleteBtn = true;
                  } else {
                    console.log('no permissions');
                  }
                } else {
                  console.log('no events');
                }
              }
              this.spinner.hide();
            },
            (error) => {console.log(error)}
          );
        }
      );

    //get id in edit mode 
    this.route.params.subscribe(
      (params: Params) => {
        this.pageId = params['trainnerListId'];
        this.dashBoardService.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
          (responce) => {
            console.log(responce);
            this.trainnersData = responce['users'];
            this.count = responce['count'];
            this.perPagePagenation = responce['per_page'];
            this.spinner.hide();
          },
          (error) => {
            console.log(error);
          }
        );
      }
    );

  }

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

  checkIfAllSelected() {
    this.selectedAll = this.trainnersData.every(function(item:any) {
      return item.selected == true;
    });
  };
  
  //filtter function
  filtterFunc(data) {
  this.trainnersData = [];
  console.log(data.target.value);
  const dataSearch = data.target.value;
  this.currentPage = 1;
  console.log('search curent page', this.currentPage);
  this.dashBoardService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
    (responce) => {
      console.log(responce);
      this.trainnersData = responce['users'];
      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.trainnersData = [];
  //console.log(pagenationNumber);
  //console.log(this.pageId);
  this.dashBoardService.getListData(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
  (responce) => {
    console.log('search result ', responce);
    this.trainnersData = responce['users'];
    this.count = responce['count'];
    this.perPagePagenation = responce['per_page'];
    console.log(this.trainnersData);
    this.spinner.hide();
  },
  (error) => {
    console.log(error);
    this.spinner.hide();
   }
  );
};
  
  
//determine the list count from select element
onGetValue(event) {
  this.spinner.show();
  this.trainnersData = [];
  this.dataTableNumber = event.target.value;
  this.dashBoardService.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
    (responce) => {
      console.log(responce);
      this.trainnersData = responce['users'];
      this.count = responce['count'];
      this.perPagePagenation = responce['per_page'];
      this.spinner.hide();
    },
    (error) => {
      console.log(error);
      this.spinner.hide();
    }
  );
}

onDelete() {

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

  console.log(this.trainnersListIds);
  if(this.trainnersListIds.length > 0) {
    const dialogRef = this.modal.alert()
    .size('sm')
    .showClose(true)
    .title('تأكيد الحذف')
    .body(`
        <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
        `)
    .open();

      dialogRef.result
      .then( result => 
        this.dashBoardService.deleteItem(this.trainnersListIds, this.pageId).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم الحذف');
              this.spinner.show();
              this.trainnersData = [];
              this.dashBoardService.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
                (responce) => {
                  console.log(responce);
                  this.count = responce['count'];
                  this.perPagePagenation = responce['per_page'];
                  this.trainnersData = responce['users'];
                  console.log(this.trainnersData);
                  this.spinner.hide();
                },
                (error) => {
                  console.log(error);
                }
              )
            },
            (error) => {
              console.log(error);
              this.toastr.error('حدث خطأ رجاء الانتظار وحاول ثانيه');
              this.spinner.hide();
            }
        )
      );
  } else {
    this.toastr.warning('لم يتم أختيار أي عنصر للحذف !');
  }
};

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

//edit function
 onEdit(editId) {
  this.router.navigate(['service/' + this.userId + '/' + this.serviceId + '/trainer/edit/' + editId]);
}

}
