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


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

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

    dataList = [];
    pages= [];
    pageId: number;
    Ids = [];
    count: number;
    perPagePagenation: number;
    currentPage:number = 1;
    filtterStatus = 'all';
    selectedAll: any;
    userLoginId:number;
    serviceId:number;
    dataTableNumber: number = 5;
    //absorpationListIds = [];
    dataListIds = [];
    
    counter$: Observable<number>;
    counter = 180;

    typeList: string;

  ngOnInit() {

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

      //reload page every 10 seconds
      setTimeout(function(){
        location.reload(); 
      },180000);

      this.counter$ = timer(0,1000).pipe(
        take(this.counter),
        map(() => --this.counter)
      );

      this.route.params.subscribe(
        (parmas: Params) => {
          this.pageId =  +parmas['listPageId'];
          localStorage.setItem('pageIdActive', parmas['listPageId']);

          if(this.pageId == 56) {

            this.typeList = 'متابعه البلاغات الصادره';

            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].id == 56) {
                          if(this.pages[i]['permissions'][0].name == 'follow_up_communications') {
                            this.authSer.showEditBtn = true;
                          } else {
                            console.log('no permissions');
                          }
                        } else {
                          console.log('no events');
                        }
                      }
                      this.spinner.hide();
                    },
                    (error) => {console.log(error)}
                  );
                }
              );
              
              console.log('current page',this.pageId)
              this.dashboardSer.getListData(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
                (response) => {
                  this.dataList = response['communications'];
                  console.log('dataList', this.dataList);
                  this.count = response['count'];
                  this.perPagePagenation = response['per_page'];
                  this.returnEditData();
                },
                (error) => {
                  console.log(error);
                }
        
              );
          } else if(this.pageId == 58) {

            this.typeList = 'متابعه البلاغات الوارده للصيانه';

            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].id == 58) {
                          if(this.pages[i]['permissions'][0].name == 'follow_up_communications_for_admin_maintenance') {
                            this.authSer.showEditBtn = true;
                          } else {
                            console.log('no permissions');
                          }
                        } else {
                          console.log('no events');
                        }
                      }
                      this.spinner.hide();
                    },
                    (error) => {console.log(error)}
                  );
                }
              );
              
              console.log('current page',this.pageId)
              this.dashboardSer.getListData(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
                (response) => {
                  console.log(response);
                  this.dataList = response['communications'];
                  this.count = response['count'];
                  this.perPagePagenation = response['per_page'];
                  this.returnEditData();           
                },
                (error) => {
                  console.log(error);
                }
        
              );
          } else if(this.pageId == 59) {

            this.typeList = 'متابعه البلاغات الوارده للإداره';

            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].id == 59) {
                          if(this.pages[i]['permissions'][0].name == 'follow_up_communications_for_adminstration') {
                            this.authSer.showEditBtn = true;
                          } else {
                            console.log('no permissions');
                          }
                        } else {
                          console.log('no events');
                        }
                      }
                      this.spinner.hide();
                    },
                    (error) => {console.log(error)}
                  );
                }
              );
              
              console.log('current page',this.pageId);

              this.dashboardSer.getListData(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
                (response) => {
                  console.log('beforre', response);
                  this.dataList = response['communications'];
                  this.count = response['count'];
                  this.perPagePagenation = response['per_page'];
                  this.returnEditData();           
                  console.log('afteeeeeer', response);
                },
                (error) => {
                  console.log(error);
                }
              );
          } else if(this.pageId == 60) {
            this.typeList = 'متابعه البلاغات الوارده للقسم';
            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].id == 60) {
                          if(this.pages[i]['permissions'][0].name == 'follow_up_communications_for_department') {
                            this.authSer.showEditBtn = true;
                          } else {
                            console.log('no permissions');
                          }
                        } else {
                          console.log('no events');
                        }
                      }
                      this.spinner.hide();
                    },
                    (error) => {console.log(error)}
                  );
                }
              );
              
              console.log('current page',this.pageId);

              this.dashboardSer.getListData(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
                (response) => {
                  console.log('beforre', response);
                  this.dataList = response['communications'];
                  this.count = response['count'];
                  this.perPagePagenation = response['per_page'];
                  this.returnEditData();           
                  console.log('afteeeeeer', response);
                },
                (error) => {
                  console.log(error);
                }
              );
          }

        }
      );

      
  }

  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.dashboardSer.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.dataList = responce['communications'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        this.returnEditData();
        console.log('filtter count', this.count);
        console.log('filtter perPagePAgenation', this.perPagePagenation);
      },
      (error) => {
        console.log(error)
      }
    );
  };

onPageChange(pagenationNumber) {
  this.dataList = [];
  this.spinner.show();
  this.currentPage = pagenationNumber;
  console.log(pagenationNumber);
  console.log(this.pageId);
  this.dashboardSer.searchFiltterPagenation(this.pageId, pagenationNumber, this.dataTableNumber, this.filtterStatus).subscribe(
    (responce) => {
      console.log(responce);
      this.dataList = responce['communications'];
      this.count = responce['count'];
      this.perPagePagenation = responce['per_page'];
      this.returnEditData();
      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.dashboardSer.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
    (responce) => {
      console.log(responce);
      this.dataList = responce['communications'];
      this.count = responce['count'];
      this.perPagePagenation = responce['per_page'];
      this.returnEditData();
      this.spinner.hide();
    },
    (error) => {
      console.log(error);
      this.spinner.hide();
    }
  );
};

onGetValueFiltter(event) {
  console.log(event.target.value)
  this.spinner.show();
  this.dataList = [];
  const typeId = event.target.value;
  this.filtterStatus = event.target.value;
  console.log(this.filtterStatus);
  this.http.get(this.authSer.pathApi +'/page_list/' + this.pageId + '/' + this.currentPage + '/' + this.dataTableNumber + '/' + typeId).subscribe(
    (responce) => {
      console.log(responce);
      this.dataList = responce['communications'];
      this.count = responce['count'];
      this.perPagePagenation = responce['per_page'];
      this.returnEditData();
      this.spinner.hide();
      console.log('UrL>>', this.authSer.pathApi +'/page_list/' + this.pageId + '/' + this.currentPage + '/' + this.dataTableNumber + '/' + typeId)
    },
    (error) => {
      console.log(error);
    }
  );
}


//return substring of subject and check negaive and positive time 
returnEditData() {
  for(let i = 0; i < this.dataList.length; i++) {
    if(this.dataList[i].subject.length > 20) {
      this.dataList[i].subject = this.dataList[i].subject.substring(0 , 15) + '...';
    }

    // const firstChar = this.dataList[i].total_count_down.substring(0,1);
    //   console.log('first char', firstChar);
    //   if(firstChar == '-') {
    //     this.dataList[i].total_count_down = '-' + this.dashboardSer.secondsToDhms(this.dataList[i].total_count_down);
    //   }
      this.dataList[i].total_count_down = this.dataList[i].total_count_down ? this.dashboardSer.secondsToDhms(this.dataList[i].total_count_down) : '-';
      console.log(this.dataList[i].total_count_down);
  }
}

  onEdit(id: number) {
    console.log(id);
    if(this.pageId == 58) {
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/maintenanceCommunicationEdit/' + id]);
    } else if(this.pageId == 56){
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/followCommunicationEdit/' + id]);
    } else if(this.pageId == 59){
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/followCommunicationAdminEdit/' + id]); 
    } else if(this.pageId == 60) {
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/followCommunicationSecEdit/' + id]);
    }
  }

}
