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


@Component({
  selector: 'app-main-list',
  templateUrl: './main-list.component.html',
  styleUrls: ['./main-list.component.css']
})
export class MainListComponent implements OnInit {
  menuId: number;
  menuList = [];
  menuListIds = [];
  count: number;
  perPagePagenation: number;
  p: number[] = [];
  currentPage:number = 1;
  filtterStatus = '';
  selectedAll: any;
  userLoginId:number;
  serviceId:number;
  dataTableNumber: number = 5;
  pages = [];
  servicesName: string = '';

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

  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.menuId = params['menuPageId'];
      }
    );
    
    //to show / hide permissions

  this.route.parent.params.subscribe(
    (params:Params) => {
        this.userLoginId = params['userID'];
        this.serviceId = params['serviceID'];

        if(this.serviceId == 6) {
          this.servicesName = 'خدمه إداره المحتوي';
        } else if(this.serviceId == 2){
          this.servicesName = 'خدمه إداره الصفحه الخارجيه';
        }

        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 == 17) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_menu'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_menu'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_menus'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              } else if(this.pages[i].id == 18) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_external_menu'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_external_menu'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_external_menus'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }else {
                console.log('no events');
              }
            }
            this.spinner.hide();
          },
          (error) => {console.log(error)}
        );
      }
    );

    //get list data 
    this.dashBoardService.getListData(this.menuId, this.currentPage ,this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.menuList = responce['menus'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log('evennnnts', this.menuList);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
    
  }

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

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

  //filtter function
  filtterFunc(data) {
    this.menuList = [];
    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.menuId);
    this.dashBoardService.getDataUSerSearchBar(dataSearch, this.menuId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.menuList = responce['menus'];
        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.menuList = [];
      //console.log(pagenationNumber);
      //console.log(this.pageId);
      this.dashBoardService.getListData(this.menuId, pagenationNumber, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.menuList = responce['menus'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log(this.menuList);
          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_menu', data).subscribe(
  //     (responce) => {
  //       console.log(responce);
  //       this.mainService.getMainList(this.menuId, this.currentPage, this.dataTableNumber).subscribe(
  //         (responce) => {
  //           console.log(responce);
  //           this.count = responce['count'];
  //           this.perPagePagenation = responce['per_page'];
  //           this.menuList = responce['menus'];
  //           console.log(this.menuList);
  //           this.spinner.hide();
  //         },
  //         (error) => {
  //           console.log(error);
  //         }
  //       )
  //     },
  //     (error) => {console.log(error)},
  //   );
  // };

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

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

    console.log(this.menuListIds);
    if(this.menuListIds.length > 0) {
      const dialogRef = this.modal.alert()
      .size('sm')
      .showClose(true)
      .title('تأكيد الحذف')
      .body(`
          <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
          `)
      .open();
  
        dialogRef.result
        .then( result => 
          this.dashBoardService.deleteItem(this.menuListIds, this.menuId).subscribe(
              (responce) => {
                console.log(responce);
                this.toastr.success('تم الحذف');
                this.spinner.show();
                this.menuList = [];
                this.dashBoardService.getListData(this.menuId, this.currentPage, this.dataTableNumber).subscribe(
                  (responce) => {
                    console.log(responce);
                    this.count = responce['count'];
                    this.perPagePagenation = responce['per_page'];
                    this.menuList = responce['menus'];
                    console.log(this.menuList);
                    this.spinner.hide();
                  },
                  (error) => {
                    console.log(error);
                  }
                )
              },
              (error) => {
                console.log(error);
                this.toastr.error('حدث خطأ رجاء الانتظار وحاول ثانيه');
                this.spinner.hide();
              }
          )
        );
    } else {
      this.toastr.warning('لم يتم أختيار أي عنصر للحذف !');
    }
  };

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

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

}
