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


@Component({
  selector: 'app-internal-services',
  templateUrl: './internal-services.component.html',
  styleUrls: ['./internal-services.component.css']
})
export class InternalServicesComponent 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 internalService: InternalSerService) { }

  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 = [];

  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('iddddddddd', params['hospitalListId']);
        this.pageId = params['internalPageId'];
          this.typeLink = 'الخدمات الداخليه';
      }
    );

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

        this.internalService.getInternalsList(this.pageId , this.currentPage, this.dataTableNumber).subscribe(
          (responce) => {
            console.log(responce);
            this.dataList = responce['internal_services'];
            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 == 14) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_internal_service'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_internal_service'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_internal_services'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }else {
                console.log('no interanls');
              }
            }
            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.internalService.deleteDatas(this.dataListIds, this.pageId).subscribe(
              (responce) => {
                console.log(responce);
                this.toastr.success('تم الحذف');
                this.spinner.show();
                this.dataList = [];
                this.internalService.getInternalsList(this.pageId , this.currentPage, this.dataTableNumber).subscribe(
                  (responce) => {
                    console.log(responce);
                    this.dataList = responce['internal_services'];
                    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);
      this.internalService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.dataList = responce['internal_services'];
          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.dataList = [];
      //console.log(pagenationNumber);
      //console.log(this.pageId);
      this.internalService.getInternalsList(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.dataList = responce['internal_services'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log(this.dataList);
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    }

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

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

  //on edit hospital 
  onEdit(internalIndex:number) {
    console.log('service/' + this.userLoginId + '/' + this.serviceId + '/' + 'InternalServices/edit/' + internalIndex);
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'InternalServices/edit/' + internalIndex]);
  }

}
