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



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

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

  pageId: number;
  achievementsList = [];
  rolesId = [];
  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', '11');

        this.achievementsServie.getAchievementsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
          (responce) => {
            console.log(responce);
            this.achievementsList = responce['achievements'];
            this.count = responce['count'];
            this.perPagePagenation = responce['per_page'];
            this.spinner.hide();
          },
          (error) => {
            console.log(error);
          }
        )
      }
    );

    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 == 11) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_achievement'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_achievement'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_achievements'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }else {
                console.log('no roles');
              }
            }
          },
          (error) => {console.log(error)}
        );
      }
    );
  }

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

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

  //change page 
  onPageChange(pagenationNumber) {
    this.spinner.show();
    this.currentPage = pagenationNumber;
    this.achievementsList = [];
    //console.log(pagenationNumber);
    //console.log(this.pageId);
    this.achievementsServie.getAchievementsList(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.achievementsList = responce['achievements'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log(this.achievementsList);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
  };

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

  //filtter function
  filtterFunc(data) {
    this.achievementsList = [];
    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.achievementsServie.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.achievementsList = responce['achievements'];
        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)
      }
    );
  }

   //deleted function
   onDelete() {
    this.rolesId = [];
    for(let i = 0; i < this.achievementsList.length; i++) {
      if(this.achievementsList[i].selected == true) {
        this.rolesId.push(this.achievementsList[i].id);
      }
    }

    console.log(this.rolesId);

    if(this.rolesId.length > 0) {
      const dialogRef = this.modal.alert()
      .size('sm')
      .showClose(true)
      .title('تأكيد الحذف')
      .body(`
          <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
          `)
      .open();
      dialogRef.result
      .then( result =>     
        this.achievementsServie.deleteAchievement(this.rolesId).subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم الحذف');
            this.spinner.show();
            this.achievementsList = [];
            this.achievementsServie.getAchievementsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
              (responce) => {
                console.log(responce);
                this.achievementsList = responce['achievements'];
                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 roles
  onAdd(){
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'addAchievement']);
  }  

  //edit role
  onEdit(editID) {
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'achievement/edit/' + editID]);
  }

 
    

}
