import { DashboardService } from './../../../shared/dashboard.service';
import { Modal } from 'ngx-modialog/plugins/bootstrap';
import { UserService } from './../../../shared/user.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { HospitalService } from './../../../shared/hospital.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-hospital-list',
  templateUrl: './hospital-list.component.html',
  styleUrls: ['./hospital-list.component.css']
})
export class HospitalListComponent implements OnInit {

  constructor(private route: ActivatedRoute, 
    private router: Router,
    private authSer: AuthServiceService, 
    private userSer: UserService,
    private spinner: NgxSpinnerService,
    private toastr: ToastrService,
    private modal: Modal,
    private dashboardService: DashboardService,
    private hospitalService: HospitalService) {
      this.spinner.show();
     }

  dataList = [];
  dataListIds = [];
  count: number;
  perPagePagenation: number;
  p: number[] = [];
  currentPage:number = 1;
  filtterStatus = '';
  selectedAll: any;
  pageId: number;
  userLoginId:number;
  serviceId:number;
  typeLink: string = '';
  dataTableNumber: number = 5;
  pages = [];
  typeServices: string = '';

  ngOnInit() {


    //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('iddddddddd', params['hospitalListId']);
        this.pageId = params['typePageId'];
        if(this.pageId == 6) {
          this.typeLink = 'المستشفيات والمراكز';
          this.typeServices = 'خدمه إداره المحتوي';
        } else if(this.pageId == 10) {
          this.typeLink = 'الإدارات';
          this.typeServices = 'خدمه الصلاحيات';
        } else if(this.pageId == 30) {
          this.typeLink = 'المستشفيات والمراكز';
          this.typeServices = 'خدمه إداره الصفحه الخارجيه';
        } else if(this.pageId == 31) {
          this.typeServices = 'خدمه إداره الصفحه الخارجيه';
          this.typeLink = 'الإدارات';
        }
      }
    );

    //get parent params and get list hospitals
    this.route.parent.params.subscribe(
      (params: Params) => {
        this.userLoginId = params['userID'];
        this.serviceId = params['serviceID'];
        if(this.pageId == 6 || this.pageId == 30) {
          this.dashboardService.getListData(this.pageId , this.currentPage, this.dataTableNumber).subscribe(
            (responce) => {
              console.log(responce);
              this.dataList = responce['hospital_centers'];
              this.count = responce['count'];
              this.perPagePagenation = responce['per_page'];
            },
            (error) => {
              console.log(error);
            }
          );
          this.userSer.getPagesPermetiotns(this.userLoginId, this.serviceId).subscribe(
            (responce) => {
              this.pages = responce['pages'];
              console.log('paaaages', this.pages);
              for(let i = 0; i< this.pages.length; i++) {
                if(this.pages[i].id == 6) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == 'add_hospitals_centers'){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'edit_hospitals_centers'){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'delete_hospitals_centers'){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                } else if(this.pages[i].id == 30){
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == 'add_hospitals_centers_ex'){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'edit_hospitals_centers_ex'){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'delete_hospitals_centers_ex'){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                }else {
                  console.log('no roles');
                }
              }
              this.spinner.hide();
            },
            (error) => {console.log(error)}
          );
        } else if(this.pageId == 10 || this.pageId == 31) {
          
          this.dashboardService.getListData(this.pageId , this.currentPage, this.dataTableNumber).subscribe(
            (responce) => {
              console.log(responce);
              this.dataList = responce['managements'];
              this.count = responce['count'];
              this.perPagePagenation = responce['per_page'];
            },
            (error) => {
              console.log(error);
            }
          );

          this.userSer.getPagesPermetiotns(this.userLoginId, this.serviceId).subscribe(
            (responce) => {
              this.pages = responce['pages'];
              console.log('paaaages', this.pages);
              for(let i = 0; i< this.pages.length; i++) {
                if(this.pages[i].id == 10) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == 'add_management'){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'edit_management'){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'delete_managements'){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                } else if(this.pageId == 31) {
                  for(let j = 0; j < this.pages[i].permissions.length; j++) {
                    if(this.pages[i].permissions[j].name == 'add_management_ex'){
                      this.authSer.showAddBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'edit_management_ex'){
                      this.authSer.showEditBtn = true;
                    }
                    if(this.pages[i].permissions[j].name == 'delete_managements_ex'){
                      this.authSer.showDeleteBtn = true;
                    }
                  }
                }
                else {
                  console.log('no roles');
                }
              }
              this.spinner.hide();
            },
            (error) => {console.log(error)}
          );
        }
      }
    );
  }

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

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

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

      console.log(this.dataListIds);

      if(this.dataListIds.length > 0) {
      const dialogRef = this.modal.alert()
      .size('sm')
      .showClose(true)
      .title('تأكيد الحذف')
      .body(`
          <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
          `)
      .open();
        dialogRef.result
            .then( result => 
              this.dashboardService.deleteItem(this.dataListIds, this.pageId).subscribe(
                (responce) => {
                  console.log(responce);
                  this.toastr.success('تم الحذف');
                  this.spinner.show();
                  this.dataList = [];
                  if(this.pageId == 10, this.pageId == 31) {
                    this.hospitalService.getHospitalsList(this.pageId , this.currentPage, this.dataTableNumber).subscribe(
                      (responce) => {
                        console.log(responce);
                        this.dataList = responce['managements'];
                        this.count = responce['count'];
                        this.perPagePagenation = responce['per_page'];
                        this.spinner.hide();
                      },
                      (error) => {
                        console.log(error);
                      }
                    );
                  } else if(this.pageId == 6 || this.pageId == 30){
                    this.hospitalService.getHospitalsList(this.pageId , this.currentPage, this.dataTableNumber).subscribe(
                      (responce) => {
                        console.log(responce);
                        this.dataList = responce['hospital_centers'];
                        this.count = responce['count'];
                        this.perPagePagenation = responce['per_page'];
                        this.spinner.hide();
                      },
                      (error) => {
                        console.log(error);
                      }
                    );
                  }
                },
                (error) => {
                  console.log(error);
                  this.spinner.hide();
                },
              )
            );

      } else {
        this.toastr.warning('لم يتم إختيار أي عنصر للمسح !');
      }
  };

  //filtter function
  filtterFunc(data) {
    this.dataList = [];
    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);
    if(this.pageId == 6 || this.pageId == 30){
      this.dashboardService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.dataList = responce['hospital_centers'];
          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 == 10 || this.pageId == 31) {
      this.dashboardService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.dataList = responce['managements'];
          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.dataList = [];
    this.dataTableNumber = event.target.value;
    if(this.pageId == 6 || this.pageId == 30) {
      this.dashboardService.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.dataList = responce['hospital_centers'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    } else if(this.pageId == 10 || this.pageId == 31) {
      this.dashboardService.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.dataList = responce['managements'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    }
  };

  //add hospitals 
  onAdd() {
    if(this.pageId == 6 || this.pageId == 30) {
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/add/Hospital']);
    } else if(this.pageId == 10 || this.pageId == 31) {
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/add/Management']);
    }
  }

  //on edit hospital 
  onEdit(hospitalIndex:number) {
    if(this.pageId == 6 || this.pageId == 30){
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'Hospital/' + 'edithos/' + hospitalIndex]);
    } else if(this.pageId == 10 || this.pageId == 31){
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'Management/' + 'editman/' + hospitalIndex]);
    }
  }

}
