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

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

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

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

    ngOnInit() {
      //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.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 == 23) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == "add_visiting_time"){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == "edit_visiting_time"){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == "delete_visiting_times"){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                }else {
                  console.log('no events');
                }
              }
              this.spinner.hide();
            },
            (error) => {console.log(error)}
          );
        }
      );

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

      this.dashboardSer.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.visitingTimesList = responce['visiting_times'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
        },
        (error) => {
          console.log(error);
        }
      );

    } //end ngOnInit


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

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

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


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

    onDelete() {

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

      console.log(this.visitingTimesListIds);

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

          dialogRef.result
          .then( result =>
            this.dashboardSer.deleteItem(this.visitingTimesListIds, this.pageId).subscribe(
              (responce) => {
                console.log(responce);
                this.toastr.success('تم الحذف');
                this.spinner.show();
                this.visitingTimesList = [];
                this.dashboardSer.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
                  (responce) => {
                    console.log(responce);
                    this.visitingTimesList = responce['visiting_times'];
                    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 + '/visitingTime/add');
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/visitingTime/add']);
    }

    //edit function
    onEdit(editTabID) {
    localStorage.setItem('editvisitingTimeIdStorage', editTabID);
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/visitingTime/edit/'+ editTabID]);
    console.log('service/' + this.userLoginId + '/' + this.serviceId + '/visitingTime/edit/'+ editTabID);
    };

}