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



@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})

export class UsersComponent implements OnInit {

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

  pageId: number;
  usersList = [];
  usersId = [];
  count: number;
  perPagePagenation: number;
  p: number[] = [];
  currentPage:number = 1;
  filtterStatus = '';
  typeLink: string = '';
  typeService: string = '';
  selectedAll: any;
  serviceId:number;
  userLoginId:number;
  pages = [];
  dataTableNumber: number = 5;
  checkListType: boolean;

  @ViewChild('') filtterBar = '';


  ngOnInit() {

    //show spinner
    this.spinner.show();

    //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;

    //catch id of page
    this.route.params.subscribe(
      (params: Params) => {
        this.pageId = params['listPageId'];
        localStorage.setItem('pageIdActive', params['listPageId']);
        if(this.pageId == 1) {
          this.typeLink = 'المستخدمين';
          this.typeService = 'خدمه الصلاحيات';
          this.checkListType = true;
        } else if(this.pageId == 9) {
          this.typeLink = 'إنضم إلينا';
          this.typeService = 'خدمه إداره المحتوي';
          this.checkListType = false;
        }
      }
    );


    //to control of pwermision of each user
    this.route.parent.params.subscribe(
      (params: Params) => {
        this.userLoginId = params['userID']; //user login id
        this.serviceId = params['serviceID']; //service id
        if(this.pageId == 1) {


        //get pages with its permisions
        this.userSer.getPagesPermetiotns(this.userLoginId, this.serviceId).subscribe(
          (responce)=>{
            this.pages = responce['pages']; 

            for(let i = 0; i< this.pages.length; i++) {
                if(this.pages[i].id == 1) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == 'add_user'){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'edit_user'){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'delete_user'){
                      this.authSer.showDeleteBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'asign_roles_permissions_to_user'){
                      this.authSer.showPermissionsBtn = true;
                    }
                  }
                }else {
                  console.log('no users');
                }
              }
            },
            (error) => {
              console.log(error);
            }
          );
          //get list of users
          this.userSer.getPageData(this.pageId, this.currentPage , this.dataTableNumber).subscribe(
            (responce) => {
              this.usersList = responce['users'];
              console.log(this.usersList);
              for (var i = 0; i < this.usersList.length; i++) {
                this.usersList[i].selected = false;
              }
              this.count = responce['count'];
              this.perPagePagenation = responce['per_page'];
              this.spinner.hide();
            },
            (error) => {console.log(error)}
          );

        } else if(this.pageId == 9) {
          //get join us pages with its permisions
          this.userSer.getPagesPermetiotns(this.userLoginId, this.serviceId).subscribe(
            (responce)=>{
              this.pages = responce['pages'];            
              for(let i = 0; i< this.pages.length; i++) {
                  if(this.pages[i].id == 9) {
                    for(let j = 0; j < this.pages[i].permissions.length; j++) {
                      if(this.pages[i].permissions[j].name == 'add_join_us_user'){
                        this.authSer.showAddBtn = true;
                      }
                      if(this.pages[i].permissions[j].name == 'edit_join_us_user'){
                        this.authSer.showEditBtn = true;
                      }
                      if(this.pages[i].permissions[j].name == 'delete_join_us_users'){
                        this.authSer.showDeleteBtn = true;
                      }
                    }
                  }else {
                    console.log('no join us');
                  }
                }
              },
              (error) => {
                console.log(error);
              }
            );

            //get list of join us
            this.userSer.getPageData(this.pageId, this.currentPage , this.dataTableNumber).subscribe(
              (responce) => {
                console.log(responce);
                this.usersList = responce['join_wes'];
                console.log(this.usersList);
                for (var i = 0; i < this.usersList.length; i++) {
                  this.usersList[i].selected = false;
                }
                this.count = responce['count'];
                this.perPagePagenation = responce['per_page'];
                this.spinner.hide();
              },
              (error) => {console.log(error)}
            );
        }

      }
    );
  };

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

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

  //change page 
  onPageChange(pagenationNumber) {
    this.spinner.show();
    this.currentPage = pagenationNumber;
    this.usersList = [];
    //console.log(pagenationNumber);
    //console.log(this.pageId);
    if(this.pageId == 1){
      this.userSer.getPageData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.usersList = responce['users'];
          console.log(this.usersList);
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    } else if(this.pageId == 9) {
      this.userSer.getPageData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.usersList = responce['join_wes'];
          console.log(this.usersList);
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    }

  };

  //edit user function
  onEdit(id) {
    if(this.pageId == 1){
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'user/editUs/' + id]);
    } else if(this.pageId == 9){
      console.log('service/' + this.userLoginId + '/' + this.serviceId + '/' + 'joinUs/edit/' + id);
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'joinUs/edit/' + id]);
    }
  }

  //add user function
  onAddUser() {
    if(this.pageId == 1){
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'addu/user']);
    } else if(this.pageId == 9){
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'addJoinUs']);
    }
  }

  //delete users function
  onDeleteUsers() {
    this.usersId = [];
      for(let i = 0; i < this.usersList.length; i++) {
        if(this.usersList[i].selected == true) {
          this.usersId.push(this.usersList[i].id);
        }
      }

    

      if(this.usersId.length > 0) {
        const dialogRef = this.modal.alert()
        .size('sm')
        .showClose(true)
        .title('تأكيد الحذف')
        .body(`
            <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
            `)
        .open();
        dialogRef.result
        .then( result =>  
          this.userSer.deleteUser(this.usersId, this.pageId).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم الحذف');
              this.spinner.show();
              this.usersList = [];
              if(this.pageId == 1) {
                this.userSer.getPageData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
                  (responce) => {
                    console.log(responce);
                    this.usersList = responce['users'];
                    console.log(this.usersList);
                    this.spinner.hide();
                  },
                  (error) => {
                    console.log(error);
                    this.spinner.hide();
                  }
                );
              } else if(this.pageId == 9) {
                this.userSer.getPageData(this.pageId, this.currentPage , this.dataTableNumber).subscribe(
                  (responce) => {
                    console.log(responce);
                    this.usersList = responce['join_wes'];
                    console.log(this.usersList);
                    for (var i = 0; i < this.usersList.length; i++) {
                      this.usersList[i].selected = false;
                    }
                    this.count = responce['count'];
                    this.perPagePagenation = responce['per_page'];
                    this.spinner.hide();
                  },
                  (error) => {console.log(error)}
                );
              }
              
            },
            (error) => {console.log(error)},
          )
        );
      } else {
        this.toastr.warning('لم يتم إختيار أي عنصر للمسح !');
      }

  }
 
//filtter function
  filtterFunc(data) {
    this.usersList = [];
    console.log(data.target.value);
    const dataSearch = data.target.value;     
    this.currentPage = 1;
    if(this.pageId == 1){
      this.userSer.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          this.usersList = responce['users'];
          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)
        }
      );
    } else if(this.pageId == 9){
      this.userSer.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          this.usersList = responce['join_wes'];
          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)
        }
      );
    }
  }

  //get permission user
  onGetPermission(userIndex) {
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId +'/userPermission/' + userIndex]);
  }

  onGetValue(event) {
    this.spinner.show();
    this.usersList = [];
    this.dataTableNumber = event.target.value;
    if(this.pageId == 1){
      this.userSer.getPageData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.usersList = responce['users'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log(this.usersList);
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    } else if(this.pageId ==9){
      this.userSer.getPageData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.usersList = responce['join_wes'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log(this.usersList);
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    }
  }

}
