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-event-calendars-list',
  templateUrl: './event-calendars-list.component.html',
  styleUrls: ['./event-calendars-list.component.css']
})
export class EventCalendarsListComponent 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) { }

    eventCalendarsList = [];
    pages= [];
    pageId: number;
    eventCalendarsListIds = [];
    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.params.subscribe(
        (parmas: Params) => {
          this.pageId = parmas['listPageId'];
          localStorage.setItem('pageIdActive', parmas['listPageId']);
        }
      );

      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 == 25) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == "add_event_calendar"){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == "edit_event_calendar"){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == "delete_event_calendars"){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                }else {
                  console.log('no event calendars');
                }
              }
              this.spinner.hide();
            },
            (error) => {console.log(error)}
          );
        }
      );

   

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

    } //ngOnInit

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

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

  //filtter function
  filtterFunc(data) {
  this.eventCalendarsList = [];
  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.eventCalendarsList = responce['event_calendars'];
      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.eventCalendarsList = [];
  //console.log(pagenationNumber);
  //console.log(this.pageId);
  this.dashboardSer.getListData(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
  (responce) => {
      console.log(responce);
      this.eventCalendarsList = responce['event_calendars'];
      this.count = responce['count'];
      this.perPagePagenation = responce['per_page'];
      console.log(this.eventCalendarsList);
      this.spinner.hide();
    },  
    (error) => {
      console.log(error);
      this.spinner.hide();
    }
  );
};


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

onDelete() {

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

  console.log(this.eventCalendarsListIds);

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

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

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


}
