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


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

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

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

  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) => {
        console.log(params['rolesPageId']);
        this.pageId = params['rolesPageId'];
      }
    );

  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].name == 'المجموعات') {
              for(let j = 0; j < this.pages[i].permissions.length; j++) {
                if(this.pages[i].permissions[j].name == 'add_role'){
                  this.authSer.showAddBtn = true;
                }
                if(this.pages[i].permissions[j].name == 'edit_role'){
                  this.authSer.showEditBtn = true;
                }
                if(this.pages[i].permissions[j].name == 'delete_role'){
                  this.authSer.showDeleteBtn = true;
                }
              }
            }else {
              console.log('no roles');
            }
          }
        },
        (error) => {console.log(error)}
      );
    }
  );

    this.rolesService.getRolesList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log('responce', responce);
        this.rolesList = responce['roles'];
        for (var i = 0; i < this.rolesList.length; i++) {
          this.rolesList[i].selected = false;
        }
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
  }

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

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

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

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

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

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

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

    this.rolesService.deleteUser(this.rolesId).subscribe(
      (responce) => {
        console.log(responce);
        this.toastr.success('تم الحذف');
        window.location.reload();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      },
    );
  }

  //add roles
  onAddRole(){
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'addRole']);
  }  

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

  //go to report 
  onGetReport(id:number, typeReport: string) {
    if(typeReport == 'permission_report'){
      this.router.navigate(['roleReport/' + id]);
    } else if (typeReport == 'user_report') {
      this.router.navigate(['userInRoleReport/' + id]);
    }
  }
    
}


