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

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

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

    pageId: number;
    eventsList = [];
    eventsListIds = [];
    count: number;
    perPagePagenation: number;
    //p: number[] = [];
    currentPage:number = 1;
    filtterStatus = '';
    selectedAll: any;
    userLoginId:number;
    serviceId:number;
    dataTableNumber: number = 5;
    pages = [];

  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.pageId = params['listPageId'];
        localStorage.setItem('pageIdActive', '8');
      }
    );

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

    //get list data 
    this.eventService.getEventsList(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.eventsList = responce['events'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log('evennnnts', this.eventsList);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
      }
    );

  }


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

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

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

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

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

    console.log(this.eventsListIds);

    if(this.eventsListIds.length > 0) {

      const dialogRef = this.modal.alert()
      .size('sm')
      .showClose(true)
      .title('تأكيد الحذف')
      .body(`
          <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
          `)
      .open();
  
        dialogRef.result
        .then( result => 
          this.eventService.deleteEvent(this.eventsListIds).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم الحذف');
              this.spinner.show();
              this.eventsList = [];
              this.eventService.getEventsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
                (responce) => {
                  console.log(responce);
                  this.eventsList = responce['events'];
                  this.count = responce['count'];
                  this.perPagePagenation = responce['per_page'];
                  this.spinner.hide();
                },
                (error) => {
                  console.log(error);  
                }
              );
            },
            (error) => {
              console.log(error);
              this.spinner.hide();
            },
          )
        );
    } else {
      this.toastr.warning('لم يتم إختيار أي عنصر للمسح !');
    }
  };

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

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

}
