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

    externalAchievementsList = [];
    pages= [];
    pageId: number;
    externalAchievementsListIds = [];
    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 == 27) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == "add_external_achievement"){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == "edit_external_achievement"){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == "delete_external_achievements"){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                }else {
                  console.log('no achievements ');
                }
              }
              this.spinner.hide();
            },
            (error) => {console.log(error)}
          );
        }
      );

    

      this.dashboardSer.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.externalAchievementsList = responce['external_achievements'];
          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.externalAchievementsList.length; i++) {
          this.externalAchievementsList[i].selected = this.selectedAll;
        }
      };

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

      //filtter function
      filtterFunc(data) {
      this.externalAchievementsList = [];
      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.externalAchievementsList = responce['external_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)
        }
      );
    };

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


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

    onDelete() {

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

      console.log(this.externalAchievementsListIds);

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

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

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

}
