import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { GetdevdetailComponent } from '../const/getdevdetail/getdevdetail.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import { ContactService } from '../contact.service';
import { Params, Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { window } from 'angular-bootstrap-md/utils/facade/browser';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { DatainjectionService } from '../datainjection.service';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { NotificationComponent } from '../notification/notification.component';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import { Observable } from 'rxjs/Rx';
import * as moment from 'moment';
import { Subject } from 'rxjs/Subject';
declare var Chart :any;
declare var swal : any;

import 'rxjs/add/operator/debounceTime';
import { SharedDevicesComponent } from './shared-devices/shared-devices.component';
import { DemoVideosComponent } from './demo-videos/demo-videos.component';
import { ManualAddressComponent } from './manual-address/manual-address.component';
import { TranslateService } from 'ng2-translate';
import {AnnouncementComponent} from './announcement/announcement.component'
declare var $: any;

declare var google: any;
declare var ol : any;

@Component({
  selector: 'app-const',

  templateUrl: './const.component.html',
  styleUrls: ['./const.component.css'],
  providers: [SidebarComponent, NotificationComponent],

})
export class ConstComponent implements OnInit {
//   {_id: "power", count: 3}
// // 1: {_id: "immo", count: 3}
// // 2: {_id: "overspeed", count: 23}
// // 3: {_id: "IGN", count: 543}
// // 4: {_id: "theft", count: 145}
// // 5: {_id: "SOS", count: 6}
  notificationArray=[{name:'Power',type:'power',count:0},{name:'Ignition',type:'IGN',count:0},{name:'Parking',type:'theft',count:0},
                     {name:'Toll',type:'toll',count:0},{name:'Over Speed',type:'overspeed',count:0},{name:'Geo-Fence',type:'Geo-Fence',count:0} ]
  @ViewChild('widgetsContent') widgetsContent: ElementRef;
  superAdmin: Boolean = false;
  modelChanged: Subject<string> = new Subject<string>();
  fs: any;
  ls: any;
  cond: Boolean = false;
  roadShow:Boolean=true;
  point: any = 0;
  loading: any; loadingName: any;
  unloading: any; unloadingName: any;
  not_on_root: any; norName: any;
  address_show: string;
  deviceData: any;
  baba: any[];
  arrival_time: Date;
  Durations: string;
  status_toShow: string;
  lattitude: any;
  longitude: any;
  filtes: any;
  total_final: any;
  vehicleDetail: any;
  add_dev: boolean;
  textStatus: string;
  fuelUrl = "";
  Running: any;
  iconHide: boolean = true;
  groupId: any;
  groupName: any;
  fuelvariable : any = "FUEL (LITRE)";
  fuelflag = 'l';

  setTimeOut = {
    value: 20,
    viewValue: "20 Seconds"
  };
  timout = [{
    value: 10,
    viewValue: "10 Seconds"
  },
  {
    value: 20,
    viewValue: "20 Seconds"
  },
  {
    value: 30,
    viewValue: "30 Seconds"
  }]


  interval: any;
  changeTime: any;
  pwrURL: any;
  gpsImg: string;
  gStatus: string;
  pStatus: string;

  showDataByGroup = function () {
    return this.contactService.getService();
  }
  fuelCount=[{
    fuel : 'Diesel',
    price: 0 ,
    unit : 'litre'
},{
  fuel : 'Petrol',
  price: 0 ,
  unit : 'litre'
}]
  devIcon: string;
  roadicon = "../../assets/image/roadBoard.jpg";
  supAdm: any;
  DealerID: any;
  expiredDevices: any;
  expired_ids: any;
  ACImg: string;
  aStatus: string;
  deviceBarChart: any;
  devicePiChart: any;
  devicePiChart_1: any;
  notifArr: any=[];
  gps_column: Boolean = true;
  ac_column: Boolean = true;
  power_column: Boolean = true;
  gsm_column: Boolean = true;
  ignition_column: Boolean = true;
  ext_volt: Boolean = true;
  isOrganisation: any;
  userState: any;
  currState: any;
  leftPaddle: HTMLCollectionOf<Element>;
  rightPaddle: HTMLCollectionOf<Element>;
  itemsLength: any;
  itemSize: any;
  paddleMargin: number;
  getMenuWrapperSize: () => any;
  menuWrapperSize: any;
  menuVisibleSize: any;
  getMenuSize: () => number;
  menuSize: any;
  menuInvisibleSize: number;
  showButton:boolean=false
  getMenuPosition: () => any;

  myaccount() {

    this.cond = false
    this.router.navigateByUrl("accountSettings");



  }
  scrollLeft(){
   this.showButton=!this.showButton
    this.widgetsContent.nativeElement.scrollLeft -= 260;
  }

  scrollRight(){
    this.showButton=!this.showButton
    this.widgetsContent.nativeElement.scrollLeft += 260;
  }

  a() {

    if (this.point == 0) {
      this.cond = true;
      this.point++;
    }
    else if (this.point % 2 == 0) {
      this.cond = true;
      this.point++;
    }
    else {
      this.cond = false
      this.point++;
    }
  }
  report() {

    this.cond = false
    this.router.navigateByUrl("device-report");

  }
  report_speed() {

    this.cond = false
    this.router.navigateByUrl("device-report/device-speed-report");
  }
  emailid: any;
 
  or: any;
  onn_time: any;
  min: any;
  corect_min: any;
  hr: any
  from: any;
  to: any;
  devicess: any;
  Load: Boolean = false;;

  // public pieChartLabels:string[] = ['Moving', 'Idle', 'Engine Off'];
  //   public pieChartData:number[] = [500, 200, 100];
  //   public pieChartType:string = 'pie';
  public doughnutChartLabels: string[] = ['Stopped', 'Maintenance', 'Idle', 'Running', 'Out off reach', 'No GPS'];

  public runningDoughnutChartLabels: any = ['Transit', 'Reverse Transit', 'No Trip'];
  public stoppedDoughnutChartLabels: string[] = ['Less than 2 hours', 'More than 2 hours', 'More than 6 hours', 'More than 24 hours'];
  public idleDoughnutChartLabels = ['Less than 15 min.', 'More than 1 hr.', 'More than 15 min.', 'More than 30 min.'];
  public maintenanceDoughnutChartLabels = ['Maintenance'];
  public noGPSDoughnutChartLabels = ['No GPS'];
  public outofreachDoughnutChartLabels = ['Out Of Reach'];



  public doughnutChartData: number[] = [1];
  public doughnutChartType: string = 'doughnut';
  public doughnutradius_width = [20, 20, 20, 20, 20, 20];



  public doughnutChartLabels_running: string[] = ['Vehicles Running'];
  public doughnutChartData_running: number[] = [1];
  public doughnutChartData_idle: number[] = [1];
  public doughnutChartData_stopped: number[] = [1];
  public Dmaintanance = [1]
  public doughnutChartData_our = [1];

  // public doughnutChartLabels:string[] = ['Vehicles Stopped', 'Vehicles under Maintenance', 'Idle Vehicles' , 'Out off reach Vehicles','Vehicles Running'];

  /////piechart-start
  public barChartOptions: any = {
    scaleShowVerticalLines: false,
    responsive: true
  };
  public barChartLabels = [];
  public barChartType: string = 'bar';
  public barChartLegend: boolean = true;

  public barChartData = [{ data: [0, 0, 0, 0, 0, 0, 0], label: 'Total Distance' }];



  MapLoad: any;
  ign() {
    this.router.navigateByUrl("device-report/ign-report");

  }
  
  /* ................................................................ */
  // plotgraph(a) {

  //   var tempTime = new Date()
  //   var time;
  //   var t = new Date(tempTime.getFullYear(),
  //     tempTime.getMonth(),
  //     tempTime.getDate(),
  //     23, 59, 59, 999);
  //   /*  
  //    time = new Date(t.getTime() + 1).toISOString() */
  //   time = new Date().setHours(0, 0, 0, 0) - 1;
  //   let timee = new Date(time).toISOString();
  //   /* this.Load = true; */
  //   this.MapLoad = true;
  //   this.contactService.getDashboardGraph(a.did, timee).subscribe(

  //     data => {
  //       this.devicess = data


  //       this.randomize(this.devicess);

  //     });


  // }

  public randomize(a): void {

    let data = [];
    let label = [];

    this.barChartLabels.length = 0;
    if (this.devicess.length < 7) {
      for (var q = 0; q < (7 - this.devicess.length); q++) {
        var lastDate = this.devicess[this.devicess.length - 1].Date
        this.devicess.push({
          "Toal_Dis": 0,
          "Date": new Date(new Date(lastDate).getTime() + (1000 * 60 * 60 * 24)).toISOString()
        })
      }
    }

    for (var t = 0; t < this.devicess.length; t++) {
      var day = 0;
      var month = 0;
      var year = 0;
      var final_date = null;
      data.push(parseFloat(this.devicess[t].Total_Dis).toFixed(2));
      // var g = new Date(this.devicess[t].Date);

      //   day = g.getDate()+1; 
      //    month = g.getMonth()+1; 
      //    year = g.getFullYear();
      final_date = moment(this.devicess[t].Date).add(1, 'ms').format('DD/MM/YYYY');
      //  final_date = day+"/"+month+"/"+year
      this.barChartLabels.push(final_date);

    }

    let clone = JSON.parse(JSON.stringify(this.barChartData));
    let clone2 = JSON.parse(JSON.stringify(this.barChartLabels));
    clone[0].data = data;

    // this.barChartLabels=label;
    this.barChartData = clone;
    /* this.Load = false; */
    this.MapLoad = false;

  }
  /////piechart-end


  public chartHovered(e: any): void {

  }


  public chartClicked(e: any): void {


  }
  geo() {
    this.router.navigateByUrl("geofencing");

  }
  ideal() {
    this.router.navigateByUrl("device-report/ideal-report");
  }

  vehicleRoute() {
    this.router.navigateByUrl("vehicleRoute");

  }

  report_map() {
    this.router.navigateByUrl("routeMapping");

  }

  Ddetail() {
    this.router.navigateByUrl("driverdetail");
  }
  DModel() {
    this.router.navigateByUrl("deviceModel");
  }
  VType() {
    this.router.navigateByUrl("VehicleType");
  }



  driverPerformance() {
    this.router.navigateByUrl("device-report/Driver-performance");
  }


  notification() {
    this.router.navigateByUrl("notifications");
  }


  openNav() {
    /*  document.getElementById("myNav").style.width = "100%";
  */
    this.router.navigateByUrl("location");

  }
  openDialog4(type) {
    var datasets

    if (type == "idel") {

      datasets = this.idle_ids;

    }
    else if (type == "stop") {
      datasets = this.off_ids;
    }
    else if (type == "maintain") {
      datasets = this.maintenance_ids
        ;
    }
    else if (type == "outoff") {
      datasets = this.outofreach_ids;
    }
    let dialogRef = this.dialog.open(GetdevdetailComponent, {
      width: '903px',
      data: { Type: type, dataset: datasets }
    });

    dialogRef.afterClosed().subscribe(result => {


      if (result == "OKK") {

      }
      else if (result == "No_Dev") {


      }
    });
  }


  constructor(public dialog: MdDialog, private router: Router, private contactService: ContactService, private injectData: DatainjectionService, private activatedRoute: ActivatedRoute,
     private val: SidebarComponent, private inject: DatainjectionService, private notify: NotificationComponent,public translate: TranslateService) {

    window.localStorage['GetDevData'] = 'True'
    // console.log("p1");
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      // console.log('p3');
      this.aa = params['_status'];

      if (this.aa != "OK") {
        window.localStorage['checker'] = 'Data'
      }
      else {
        window.localStorage['checker'] = params['_status'];
      }

    });

   this.latLongDetail()
  }
  logout() {
    window.localStorage.clear();
    this.router.navigateByUrl("login");
  }
  devi() {
    this.router.navigateByUrl("dashboard");

  }
  soon() {
    this.ngOnInit();
    this.router.navigateByUrl("const");

  }

  Poiview() {
    this.router.navigateByUrl("poilist");
  }

  summaryReport() {

    this.cond = false
    this.router.navigateByUrl("device-report/summary-report");
  }

  geofancingReport() {
    this.cond = false
    this.router.navigateByUrl("device-report/geofancing");
  }

  overspeed() {
    this.cond = false
    this.router.navigateByUrl("device-report/overspeed");

  }
  routeViolation() {
    this.cond = false
    this.router.navigateByUrl("device-report/routeViolation");

  }

  stoppage_report() {
    this.cond = false
    this.router.navigateByUrl("device-report/stoppage_report");

  }
  ignition_report() {
    this.cond = false
    this.router.navigateByUrl("device-report/ignition_report");


  }

  alert_report() {
    this.cond = false
    this.router.navigateByUrl("device-report/alert_report");


  }
  trip_report() {
    this.cond = false
    this.router.navigateByUrl("device-report/trip_report");

  }

  group() {
    this.cond = false
    this.router.navigateByUrl("group_view");
  }


  notifications() {
    this.cond = false
    this.router.navigateByUrl("notifications");
  }

  distance_report() {
    this.cond = false
    this.router.navigateByUrl("device-report/distance_report");
  }

  dealerInfo() {
    this.cond = false
    this.router.navigateByUrl("dealerInfo");
  }

  AC_report() {
    this.cond = false
    this.router.navigateByUrl("device-report/ac_report");
  }

  fuel_report() {
    this.cond = false
    this.router.navigateByUrl("device-report/fuel_report");
  }


  new() {

    this.router.navigateByUrl("new");

  }
  addcus() {
    this.router.navigateByUrl("add");
  }
  total_vech: any;
  idle_vech: any;
  off_vech: any;
  maintanance: any;
  useridd: any;
  final: any;
  foods = [];
  userID: any;
  OutOfReach: any;
  no_data: any;
  expire_status
  custtype: any;
  cust: Boolean = false;
  //new:any
  // vewdev(id,name,type){

  //   if(type=="Tracker"){

  //     this.router.navigateByUrl("location?_dname="+name+"_id="+id);


  //   }
  //   else{
  //   this.router.navigateByUrl("account?_did="+id+"."+name); 
  //   }
  // }

  refreshsidebar(data, id) {

    let arr = []
    for (var q = 0; q < data.length; q++) {
      let a = {
        "Device_Name": data[q],
        "Device_ID": id[q]
      }
      arr.push(a)
    }

  }


  runnig: any;
  idle_ids: any;
  maintenance_ids: any;
  off_ids: any;
  outofreach_ids: any;
  checker: any;
  aa: any;
  subscription: any;
  timer: any;
  timer_out: any;
  runnigg: any;
  alldevvice: any;
  id_all: any;
  id_running: any;
  id_idel: any;
  id_stop: any;
  id_main: any;


  id_out: any;
  before: any;
  mb: any;
  mobile: any;
  logoutbut: boolean;
  dealer: boolean;
  idle_duration: any;
  off_duration: any;
  running_details: any;
  no_gps_name: any;

  mydealer() {
    window.localStorage['token'] = window.localStorage['Dealer_token'];
    localStorage.removeItem('devices');
    window.localStorage['DataUpdate'] = 'True';
    if (window.localStorage['DataLoaded'] = 'True') {
      window.localStorage['Custumer'] = 'OFF'
      this.router.navigateByUrl("add")
      // this.router.navigateByUrl("const?_status="+"OK");
    }
  }
  logo: any;
  text: any;
  private socket_Ing
  savedInt: any;
  ngOnInit() {
    this.Load = true;
    this.foods = [];
    this.savedInt = JSON.parse(localStorage.getItem('refreshInterval'))
    if (this.savedInt) {
      this.setTimeOut.value = this.savedInt;
  
    }

    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.isOrganisation = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isOrganisation;
    console.log('JSON.parse(window.atob(window.localStorage.token.split(".")[1]))',JSON.parse(window.atob(window.localStorage.token.split(".")[1])));

    var alpha = JSON.parse(window.atob(window.localStorage.token.split(".")[1]));
    // console.log(alpha);
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    var fuelvalue  = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).fuel_unit;
    //   this.vehicleDetail = JSON.parse(window.localStorage.getItem('devices'));

    var dashboard_content  = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).dashboard_column;
    console.log('dashboard_content',dashboard_content);

    this.gps_column = dashboard_content.gps_column ; 
    this.ac_column = dashboard_content.ac_column ;
    this.power_column =  dashboard_content.power_column ;
    this.gsm_column =  dashboard_content.gsm_column  ;
    this.ignition_column =  dashboard_content.ignition_column ; 
    this.ext_volt =  dashboard_content.ext_volt ;
// this.door_column: false
// this.temp_column: false
// this.charging_column: false
    if(this.superAdmin){
      console.log("NDDDDDDDDDDDDDJSSSSSSSSSSSSSSSSSSSSSSS");
      
      this.supAdm = this.useridd;
    }
    if(this.custtype){
      this.DealerID = this.useridd
    }

     
   console.log("Cust!!!!!!!!!!!!!!!!!!!!!!!");

    if(fuelvalue != undefined){
      if(fuelvalue == "PERCENTAGE"){
        this.fuelvariable = "FUEL (PERCENTAGE)"; 
        this.fuelflag = 'p';
      }else{
        this.fuelvariable  = "FUEL (LITRE)" ; 
        this.fuelflag = 'l';
      }
    }

    //   this.abc(this.vehicleDetail);


    if (this.custtype == true) {
      this.cust = true;
    }
    if (this.mb.charAt(0) == "n") {
      this.mb = ' '
    }

    if (window.localStorage['Custumer'] == 'ON') {
      this.logoutbut = false
      this.dealer = true
    }
    else {
      this.logoutbut = true
    }

    this.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];

    this.to = new Date().toISOString();
    var d = new Date();
    let a = d.setHours(0, 0, 0, 0)
    this.from = new Date(a).toISOString();

    var dataRoutedFromGroups = this.showDataByGroup();
    if (dataRoutedFromGroups && dataRoutedFromGroups.dataSource == "GROUPS") {
      this.groupId = dataRoutedFromGroups._id;
      this.groupName = dataRoutedFromGroups.name;

    }

    this.socket_Ing = this.injectData.getSocket_gps();

    this.socket_Ing.on('connect', function (this) {
      // console.log("No function")

    });

    this.modelChanged
    .debounceTime(2000) // wait 300ms after the last event before emitting last event
    .distinctUntilChanged() // only emit if value is different from previous value
    .subscribe(myInput => {
      this.myInput = myInput;
      // console.log('debounce')
      this.sidebarData(10);

    });



    // var retrievedData = localStorage.getItem("devices");
    //  var cord = JSON.parse(retrievedData);
    //  this.final = cord; 



    this.timer = Observable.timer(100, 100);
    this.subscription = this.timer.subscribe(t => {
      var retrievedData = localStorage.getItem("devices");
      var cord = JSON.parse(retrievedData);
      this.final = cord
      if (this.final == null || !this.final) {

      }
      else {
        if (this.final.length <= 0) {

          if (localStorage.getItem("DataLoaded") == "True") {
            this.subscription.unsubscribe();
            window.localStorage['DataLoaded'] = 'False'
          }

        }
        else {
          this.final = cord


          if (localStorage.getItem("LoadGraph") == "True") {
            this.foods = []

            for (let i = 0; i < this.final.length; i++) {

              if (this.final[i].type_of_device == "Tracker") {


                let a = {
                  value: this.final[i].Device_Name,
                  viewValue: this.final[i].Device_Name,
                  did: this.final[i].Device_ID,

                }

                this.foods.push(a);
              }

            }
            this.new = this.foods[0];

            this.timer_out = true;
            this.subscription.unsubscribe();

          }

        }
      }

    });



    // history.pushState(null, null, document.URL);
    // window.addEventListener('popstate', function () {
    //   history.pushState(null, null, document.URL);
    // });



    this.socket_Ing = this.injectData.getSocket_gps();

    // this.socket_Ing.on('connect', function (this) {


    // });

    this.reminderVal = this.reminderType[3].value;
    this.fuelUrl = '../../assets/image/nofuel.png'
    this.getGraphFunction();
    this.sidebarData(10);
    this.timeIntervalRefresh()
    //  this.Ing_Status()
    // if((this.superAdmin === false)&&(this.custtype === false)){
    //   this.vehicleUtilizationGraph();
    //   this.expenseChart();
    // }

    if((this.superAdmin === false)&&(this.custtype === false)){
      this.vehicleUtilizationGraph();
      this.expenseChart();
      this.utilisationChart();
      this.vehicleReminder();
    }
    if((this.superAdmin === true)||(this.custtype === true)){
      this.getTotalDeviceCount();
      this.getTotalExpiredDeviceCount();
      this.getTotalRenewedDeviceCount();
    }
 

    this.getApiKey();

    this.getuserObject();
    this.getLanguage();
    this.getNotificationCount()
  }


  notificationCount=[]
  getNotificationCount(){
    this.contactService.get('/notifs/getNotificationsCount?user='+this.useridd+'&from='+this.from+'&to='+this.to).subscribe((res:any)=>{
      console.log(res);
      for(var i=0;i<res.length;i++){
        for(var j=0;j<this.notificationArray.length;j++){
          // console.log(res[i]._id,"==",this.notificationArray[j].type);
          
          if(res[i]._id==this.notificationArray[j].type){
            this.notificationArray[j].count=res[i].count
          }
        }
       
      }
    
    })
  }


  getuserObject(){
    this.contactService.getImagePath(this.useridd).subscribe(res=>{
    
      if(res.timezone==="Asia/Kolkata"){
        this.fuelCard = true;
      }
   
    })
  }  

  fuelCard = false;


  getGraphFunction() {

    this.contactService.getDashboard(this.emailid, this.from, this.to, this.useridd, this.groupId,this.supAdm,this.DealerID).subscribe(
      data => {
        console.log('datadatadatadatadaata=>',data);
        localStorage.setItem('dashboardCount',JSON.stringify(data))
        this.devicess = data
        this.total_vech = this.devicess.Total_Vech;
        this.idle_vech = this.devicess["Ideal Devices"];
        this.off_vech = this.devicess["OFF Devices"];
        this.maintanance = this.devicess["Maintance Device"];
        this.expiredDevices = this.devicess["expire_status"];
        this.OutOfReach = this.devicess["OutOfReach"];
        this.no_data = this.devicess["no_data"]?this.devicess["no_data"]:0;
        this.Running = this.devicess["running_devices"];
        this.expire_status= this.devicess["expire_status"];
        // this.idle_duration = this.devicess.idle_duration;
        // this.off_duration = this.devicess.off_duration;

        let a = this.idle_vech + this.off_vech + this.maintanance + this.OutOfReach
        let b = this.total_vech - a;

        // this.idle_ids = this.devicess.idle_name
        // this.maintenance_ids = this.devicess.maintenance_name
        // this.expired_ids = this.devicess.expire_name
        // this.off_ids = this.devicess.off_name
        // this.runnigg = this.devicess.runnig_name
        // this.outofreach_ids = this.devicess.outOfReach_name
        // this.alldevvice = this.devicess.All_Device_name
        // this.no_gps_name = this.devicess.no_gps_name;
        // this.id_running = this.devicess.running_id;
        // this.id_stop = this.devicess.off_ids;
        // this.id_out = this.devicess.outofreach_ids;
        // this.id_main = this.devicess.maintenance_ids;
        // this.id_idel = this.devicess.idle_ids;

        // this.loading = this.devicess.running_details.forward.count;
        // this.unloading = this.devicess.running_details.reverse.count;
        // this.not_on_root = this.devicess.running_details.not_on_route.count;

        if (this.idle_duration && this.idle_duration.idle_lessthan15min +
          this.idle_duration.idle_morethan1hour +
          this.idle_duration.idle_morethan15min +
          this.idle_duration.idle_morethan30min > 0) {
          this.doughnutChartData_idle = [
            this.idle_duration.idle_lessthan15min,
            this.idle_duration.idle_morethan1hour,
            this.idle_duration.idle_morethan15min,
            this.idle_duration.idle_morethan30min
          ];
        }




        if (this.off_duration && this.off_duration.stopped_lessthan2hours +
          this.off_duration.stopped_morethan2hours +
          this.off_duration.stopped_morethan6hours +
          this.off_duration.stopped_morethan24hours > 0) {
          this.doughnutChartData_stopped = [
            this.off_duration.stopped_lessthan2hours,
            this.off_duration.stopped_morethan2hours,
            this.off_duration.stopped_morethan6hours,
            this.off_duration.stopped_morethan24hours
          ];
        }


        if (this.running_details && this.running_details.forward.count +
          this.running_details.not_on_route.count +
          this.running_details.reverse.count > 0) {
          this.doughnutChartData_running = [
            this.running_details.forward.count,
            this.running_details.reverse.count,
            this.running_details.not_on_route.count

          ];
        }


        // if (this.devicess.running_details.forward.names.length == 0) {
        //   this.loadingName = "NA";
        // } else {
        //   this.loadingName = this.devicess.running_details.forward.names
        // }

        // if (this.devicess.running_details.reverse.names.length == 0) {
        //   this.unloadingName = "NA";
        // } else {
        //   this.unloadingName = this.devicess.running_details.reverse.names
        // }

        // if (this.devicess.running_details.not_on_route.names.length == 0) {
        //   this.norName = "NA";
        // } else {
        //   this.norName = this.devicess.running_details.not_on_route.names
        // }
    


        this.runnig = b;

        let r = (this.off_vech / this.total_vech) * 100;
        let s = (this.maintanance / this.total_vech) * 100;
        let t = (this.idle_vech / this.total_vech) * 100;
        let u = (this.OutOfReach / this.total_vech) * 100;

        if (this.total_vech != 0) this.doughnutChartData = [];
        this.doughnutChartData.push(this.off_vech, this.maintanance, this.idle_vech, this.runnig, this.OutOfReach); 

        this.DeviceSummaryArr[0].total = this.total_vech ; 
        this.DeviceSummaryArr[1].total = this.Running; 
        this.DeviceSummaryArr[2].total = this.off_vech;
        this.DeviceSummaryArr[3].total = this.idle_vech ; 
        this.DeviceSummaryArr[4].total = this.OutOfReach;
        this.DeviceSummaryArr[5].total = this.expire_status ; 
        this.DeviceSummaryArr[6].total = this.no_data?this.no_data:0 ;
        this.utilisationChart()

        this.Load =false;
      });
  }


  showVehiclesByStatus() {


    // this.router.navigate(['/dashboard',vehStatus]);
  }

  showVehiclesByGroup = function (group) {

    this.router.navigate(['/dashboard', group._id]);
  }

  imgShow: Boolean = false;

  abc(div) {
    console.log('div=>',div);
   
    this.deviceData = div;
    var outerThis = this;
    var start_add: any;
    if (this.deviceData.length == 0) {
      this.firstcall = true;
      this.lastcall = false;
    }

    
    for (var j = 0; j < this.deviceData.length; j++) {
      if (this.deviceData[j].status_updated_at == undefined) {
        let dev_status_1 = this.deviceData[j].status ? this.deviceData[j].status : "Not available";
        this.deviceData[j].status = dev_status_1;

      } else {
          var dev_status = this.deviceData[j] ? this.deviceData[j].status : "NA";
    //  previous function for date difference conversion
      
        // this.arrival_time = new Date(this.deviceData[j].status_updated_at);

        // var curr_time = new Date();
        // var fd = new Date(this.arrival_time).getTime();
        // var td = curr_time.getTime();
        // var timedev_status_difference = td - fd;
        // var total_min = timedev_status_difference / 60000;
        // var hours = total_min / 60
        // var rhours = Math.floor(hours);
        // var minutes = (hours - rhours) * 60;
        // var rminutes = Math.round(minutes);
        // this.Durations = rhours + " " + 'hrs' + " " + rminutes + " " + 'min';

        //  previous function for date difference conversion

        // new conversion logic
        var curr_time:any = new Date();
        this.arrival_time = new Date(this.deviceData[j].status_updated_at);
        var fd:any = new Date(this.arrival_time);
        console.log('curr_time',curr_time,this.arrival_time);
        var diffInMilliSeconds= Math.abs(curr_time - fd) / 1000;

        // calculate days
        const days = Math.floor(diffInMilliSeconds / 86400);
        diffInMilliSeconds -= days * 86400;
        console.log('calculated days', days);
    
        // calculate hours
        const hours = Math.floor(diffInMilliSeconds / 3600) % 24;
        diffInMilliSeconds -= hours * 3600;
        console.log('calculated hours', hours);
    
        // calculate minutes
        const minutes = Math.floor(diffInMilliSeconds / 60) % 60;
        diffInMilliSeconds -= minutes * 60;
        console.log('minutes', minutes);
    
        let difference = '';
        if (days > 0) {
          difference += (days === 1) ? `${days} day, ` : `${days} days, `;
        }
    
        difference += (hours === 0 || hours === 1) ? `${hours} hour, ` : `${hours} hours, `;
    
        difference += (minutes === 0 || hours === 1) ? `${minutes} minutes` : `${minutes} minutes`; 
    
   // new conversion logic
          this.Durations = difference ; 
          console.log('this.Durationsthis.Durationsthis.Durationsthis.Durations',this.Durations);
      
        if (dev_status == undefined) {


          this.status_toShow = "NA";

        } else {
          this.status_toShow = dev_status + " " + "Since" + " " + this.Durations;
        }

        this.deviceData[j].status = this.status_toShow;
        this.deviceData[j].tStatus = dev_status;
        this.deviceData[j].roadShow = true;

        // console.log("Device Status =>", this.deviceData[j].status);
      
      }
      // if(this.deviceData[j].distanceVariation){
      //         if(this.deviceData[j].distanceVariation[0]=="+"){
      //           var milege=(this.deviceData[j].total_odo/100)*(Number(this.deviceData[j].distanceVariation.substring(1)))
      //           console.log("MILEGE->",milege,'-',this.deviceData[j].total_odo);
      //           this.deviceData[j].total_odo=this.deviceData[j].total_odo+milege

      //         }else{
      //           var milege=(this.deviceData[j].total_odo/100)*(Number(this.deviceData[j].distanceVariation.substring(1)))
      //           console.log("MILEGE->",milege,'-',this.deviceData[j].total_odo);
      //           this.deviceData[j].total_odo=this.deviceData[j].total_odo-milege
      //         }
      //       }
      this.getAddress(this.deviceData[j])

    }
    
    console.log('this.deviceData',this.deviceData);

   
  }

  doughnutOptions = {
    percentageInnerCutout: 80

  }

  options = {

    legend: {
      display: false
    },
    cutoutPercentage: 75

  }

  options1 = {
    legend: {
      display: false
    },
    // tooltips: {
    //   enabled: false
    // },
    cutoutPercentage: 75
  }





  //  graph according to vechical status


  // ['Vehicles Stopped', 'Vehicles under Maintenance', 'Idle Vehicles' ,'Vehicles Running', 'Out off reach Vehicles'];



  public chartColors: Array<any> = [

    {

      backgroundColor: [
        '#ffafaf',
        'rgba(152,92,16,1)',
        '#ffd366',
        'lightgreen',
        '#afe1ff',
        '#efefef'


      ],

    }
  ];
  public chartColors_running: Array<any> = [
    {
      backgroundColor: ['lime', 'lightgreen', 'green', 'darkgreen']
    }
  ];
  public chartColors_idle: Array<any> = [
    {
      backgroundColor: ['#ffeb3b94', '#ffd366', '#efb62a', '#f9b101'],
    }
  ];
  public chartColors_stopped: Array<any> = [
    {
      backgroundColor: ['#ffafaf', 'tomato', 'red', 'darkred']
    }
  ];
  public chartColors_main: Array<any> = [
    {
      backgroundColor: 'rgba(152,92,16,1)'
    }
  ];
  public chartColors_Our: Array<any> = [
    {
      backgroundColor: '#afe1ff'
    }
  ];
  public chartColors_NoGps: Array<any> = [
    {
      backgroundColor: '#efefef'
    }
  ];

   filterId :any;  

  getDeviceBYfilter(i) {
    if(i==1){
      this.skip = 0;
    }
    this.filterId = 'r';
    clearInterval(this.interval);
    var a = "RUNNING"
   // console.log(this.skip,this.limit);
    // console.log(this.DealerID);
    var status_1 = false;
    this.contactService.getDeviceByFilter_dash(a,this.emailid, this.useridd, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID,status_1) 
      .subscribe(res => {
        this.final = res.devices;
        // this.final =this.filtes;
        this.Ing_Status();
        this.abc(this.final);

      })
  }

  getDeviceBYfilterIdle(i) {
    if(i==2){
      this.skip=0;
    }
    this.filterId = 'i';

    clearInterval(this.interval);
    var a = "IDLING"
    var status_1 = false;
    this.contactService.getDeviceByFilter_dash(a,this.emailid, this.useridd, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID,status_1)
      .subscribe(res => {
        this.filtes = res.devices;
        this.abc(this.filtes);

      })


  }

  getDeviceBYfilterStop(i) {
    console.log("inside function");
    if(i==3){
      this.skip =0;
    }
    this.filterId = 's';
    // console.log(this.skip);
    clearInterval(this.interval);
    var a = "STOPPED"
    var status_1 = false;
    this.contactService.getDeviceByFilter_dash(a,this.emailid, this.useridd, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID,status_1)
      .subscribe(res => {
        // console.log("stoppedveh=>",res);
        for(var i=0 ;i<res.length;i++){
          var a = res.devices[i].Ignition ; 
          // console.log(a);
        

        }
        this.filtes = res.devices;
        this.abc(this.filtes);

      })


  }

  getDeviceBYfilterMain(i) {
    if(i==4){
      this.skip =0;
    }
    this.filterId = 'm';
    clearInterval(this.interval);
    var a = "Expired";
  
    var status_1:any;

    this.contactService.getDeviceByFilter_dash(a,this.emailid,this.useridd, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID,status_1)
      .subscribe(res => {

        this.filtes = res.devices;

        this.abc(this.filtes);

      })


  }

  getDeviceBYfilterOUR(i) {
    if(i==5){
      this.skip =0
    }
    this.filterId = 'our';
    clearInterval(this.interval);
    var a = "OUT OF REACH"
    var status_1 = false;
    this.contactService.getDeviceByFilter_dash(a,this.emailid, this.useridd, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID,status_1)
      .subscribe(res => {
        // console.log("ourveh=>",res)
        this.filtes = res.devices;

        this.abc(this.filtes);

      })
  }

  getDeviceBYfilterNOGPS(i) {
    if(i==6){
      this.skip =0;
    }
    this.filterId = 'nogpsfix';
    clearInterval(this.interval);
    var nogps = "no_gps_fix_devices";
    var status_1 = false;
    this.contactService.getDeviceByFilter_dash(nogps,this.emailid, this.useridd, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID,status_1)
      .subscribe(res => {

        this.filtes = res.devices;

        this.abc(this.filtes);

      })

  }
  getDeviceBYfilterEXPIRED(i){
    if(i==7){
      this.skip =0;
    }
     this.filterId = 'm';
    clearInterval(this.interval);
    var a = "Expired";
  
    var status_1:any;

    this.contactService.getDeviceByFilter_dash(a,this.emailid,this.useridd, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID,status_1)
      .subscribe(res => {

        this.filtes = res.devices;

        this.abc(this.filtes);

      })
  }

  getDeviceBYfilterNoData(i) {
    if (i == 7) {
      this.skip = 0;
    }
    this.filterId = 'm';
    clearInterval(this.interval);
    var a = "NO DATA";

    var status_1: any;

    this.contactService.getDeviceByFilter_dash(a, this.emailid, this.useridd, this.skip, this.limit, this.myInput, this.supAdm, this.DealerID, status_1)
      .subscribe(res => {

        this.filtes = res.devices;

        this.abc(this.filtes);

      })
  }

  alldev() {
    // console.log("localstorageComp")
    var retrievedData = localStorage.getItem("devices");
    var cord = JSON.parse(retrievedData);
    this.filtes = cord;
    this.abc(this.filtes)
  }

selectedlanguage:any
  // ----------------new login method-------------------------
  vewdevLogin(id) {
    console.log(id);
    localStorage.setItem("custId", id);
    localStorage.removeItem("in1");
    this.selectedlanguage = localStorage.getItem('appLang'); 
    this.translate.setDefaultLang(this.selectedlanguage);
    this.translate.use(this.selectedlanguage);
    this.contactService.getcustToken(id).subscribe(
      data => {
        // this.devicesss = data
        // console.log(this.devicesss)

        window.localStorage['Dealer_token'] = window.localStorage['token']
        window.localStorage['token'] =data.custumer_token;
        localStorage.removeItem('devices');
        window.localStorage['DataUpdate'] = 'True';
        window.localStorage['Custumer'] = 'ON';
        localStorage.setItem('superadmin', "ON");
     
        var chkPP = localStorage.getItem('profilePic');
        if(chkPP != null){
          localStorage.removeItem('profilePic');
        }  
        // localStorage.setItem('Dealer',"OFF");
        // localStorage.setItem('superadmin',"OFF")
        console.log('this.superAdmin',this.superAdmin);
        // debugger;
        if(this.superAdmin === true){
          localStorage.setItem('supAdminAcessToCust', 'true' ); 
        }
        if (window.localStorage['DataLoaded'] = 'True') {
          let dlrStatus = "true";

          localStorage.setItem("dlrchk", dlrStatus)

          this.router.navigateByUrl("const?_status=" + "OK");

          // console.log('testing', this.useridd);
        }
        this.deviceData=[]
        this.supAdm=undefined
        this.reload()
        this.ngOnInit()
        this.contactService.totalTicketCount.next(0);

      });
  }

  vewdev(id, name, type, expDate,lastSpeed,status) {
    // console.log(lastSpeed);

    var exStatus = status.slice(0,7);
    if(exStatus === 'Expired'){
      swal({
        title: 'Expired',
        text: "Renew Your subscription for uninterrupted service",
        type: 'warning',
        showCancelButton: false,
        confirmButtonColor: '#3085d6',
    
        confirmButtonText: 'ok'
      })

    }else{
      let currDate = new Date().getTime();
      let chkDate = new Date(expDate).getTime();
  
      var dataStatus = {
        vehicleId: id,
        vehicleName: name,
        vehicleType: type
      }
      // console.log("Inside View Dev",dataStatus);
      if (type == "Tracker") {
        localStorage.setItem('last_speed',lastSpeed );
        this.router.navigateByUrl("location?_dname=" + name + "_id=" + id);
        window.localStorage['devDetail'] = JSON.stringify(dataStatus);
      }
      else {
        localStorage.setItem('last_speed',lastSpeed );
        this.router.navigateByUrl("account?_did=" + id + "." + name);
      }
    }
  
  }


  //  changing color of icon according to response
  sidebarData(i) {
    if(i==0){
      this.skip=0;
    }
    // console.log(this.skip, this.limit);
    this.filterId = '' ;
    if (this.checker == "OK" || this.checker == "ok") {

      this.injectData.getData(this.emailid, this.useridd, this.groupId, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID).subscribe(
        (data) => {
          this.devicess = data;
          this.final = this.devicess.devices;

          this.total_final = this.final;

          if (this.final.length == 0 || this.final == null || !this.final) {
            this.add_dev = false
          
          }
          else {
            this.add_dev = true
          }
          this.Ing_Status();
          //  this.refresh();
          let val = JSON.stringify(this.final);
          localStorage.setItem("devices", val);
          window.localStorage['LoadGraph'] = 'True'
          window.localStorage['checker'] = 'Data'
          window.localStorage['DataLoaded'] = 'True'

          // window.localStorage['GetDevData'] = 'False'
        
          //  this.table();
          //  this.subscription.unsubscribe();
        },
        (err) => {
          if (err) {
          console.log(err); 
          }
        }
      )
    }
    else if (window.localStorage.DataUpdate == 'True') {


      this.final = []
      this.injectData.getData(this.emailid, this.useridd, this.groupId, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID).subscribe(
        (data) => {
          this.devicess = data
          this.final = this.devicess.devices
          this.total_final = this.final;
          if (this.final.length == 0 || this.final == null || !this.final) {
            this.add_dev = false
            this.Load = false;
          }
          else {
            this.add_dev = true
          }
          this.Ing_Status();
          //  this.refresh();

          let val = JSON.stringify(this.final);
          localStorage.setItem("devices", val);
          window.localStorage['DataUpdate'] = 'False'
          window.localStorage['LoadGraph'] = 'True'
          window.localStorage['DataLoaded'] = 'True'

          //    window.localStorage['GetDevData'] = 'False'
          // this.subscription.unsubscribe();
          this.Load = false;
          //  this.table();
          //   this.subscription.unsubscribe();

        },
        (err) => {
          if (err) {
            this.Load = false
          }
        }
      )
    }
    else if (this.checker == "Data") {

      var retrievedData = localStorage.getItem("devices");
      var cord = JSON.parse(retrievedData);
      this.final = cord
      this.total_final = this.final
      if (this.final.length == 0 || this.final == null || !this.final) {
        this.add_dev = false
        this.Load = false;
      }
      this.total_final = this.final
      window.localStorage['DataLoaded'] = 'True'
      this.Ing_Status();
      //  this.refresh();

      //  this.subscription.unsubscribe();
      //  window.localStorage['GetDevData'] = 'False'
      this.Load = false;
      // this.table();
      // this.subscription.unsubscribe();

    }

    else {

      this.injectData.getData(this.emailid, this.useridd, this.groupId, this.skip, this.limit, this.myInput,this.supAdm,this.DealerID).subscribe(
        (data) => {
          this.devicess = data
          this.final = this.devicess.devices
          this.total_final = this.final;
          if (this.final.length == 0 || this.final == null || !this.final) {
            this.add_dev = false
            this.Load = false;
          }
          else {
            this.add_dev = true
          }
          this.Ing_Status();
          //this.refresh();

          let val = JSON.stringify(this.final);
          localStorage.setItem("devices", val);
          window.localStorage['LoadGraph'] = 'True'
          window.localStorage['checker'] = 'Data'
          window.localStorage['DataLoaded'] = 'True'

          //    window.localStorage['GetDevData'] = 'False'
          this.Load = false;
          // this.subscription.unsubscribe();
          // this.table();
          //   this.subscription.unsubscribe();

        },
        (err) => {
          if (err) {
            this.Load = false;
          }
        }
      )
    }

    //   }

    // })

  }


  Ing_Status() {

    // this.ing_Arr = []
    var that = this;
    // setInterval(function(){

    for (var y = 0; y < that.final.length; y++) {
      that.socket_Ing.emit('acc', that.final[y].Device_ID)
      that.socket_Ing.on(that.final[y].Device_ID + 'acc', that.accListener(y, that.final[y]));
      var d = new Date();
      var a = d.setHours(0, 0, 0, 0);

    }



    // console.log('socket function');

    that.abc(that.total_final);
    // },(1000*that.setTimeOut.value))
  }


  imgUrlacc: any;
  ing_Arr = [];

  accListener(index, dev) {


    var outerThis = this;
    var ing
    return function (acc, from, time) {
      var newNum = "Ignition";
      var newTitle = "Ignition_Time";
      var todaysODO = "Todays_ODO"
      var newVal = acc;

      //var newTim = time;
      var dt = new Date(time);
      let day = dt.getDate();
      let month = dt.getMonth() + 1;
      let year = dt.getFullYear();

      let final_date = day + "/" + month + "/" + year
      let tm = new Date(time).toLocaleTimeString();

      let total = final_date + " " + tm

      outerThis.ing_Arr.push(from)
      dev[newNum] = newVal;
      dev[newTitle] = total;
      dev[todaysODO] = dev.today_odo

      var i = outerThis.final.indexOf(index);
      outerThis.final[i] = dev;
      outerThis.total_final = outerThis.final;


    }

  }
  imgurl: any;
  test(a, b) {
    this.textStatus = "";
    //let b = a.split("|")[0]
    var IgnTime = moment(b).format('lll');
    if (!a) {
      this.imgurl = "../../assets/image/enginena.png";
      this.textStatus = "Ignition Status: NA"
      return true;
    }
    else if (a == "1") {
      this.imgurl = "../../assets/image/enginegreen.png";
      this.textStatus = "Ignition Status: ON | Last Updated: " + IgnTime
      return true;
    }
    else if (a == "0") {

      this.imgurl = "../../assets/image/enginered.png"
      this.textStatus = "Ignition Status: OFF | Last Updated:" + IgnTime

      return true;
    }
    else {
      this.imgurl = "../../assets/image/enginena.png";
      return false;
    }
  }

  testtPower(pwr) {
    if (!pwr) {
      this.pwrURL = "../../assets/image/noPower.png";
      this.pStatus = "No Power";
      return true;
    } else if (pwr == "1") {
      this.pwrURL = "../../assets/image/power_on.png";
      this.pStatus = "Power ON";
      return true;
    } else if (pwr == "0") {
      this.pwrURL = "../../assets/image/power_off.png";
      this.pStatus = "Power OFF";
      return true;
    } else {
      return false;
    }

  }
  gsmURL:any;
  gsmStatus:any;
  testSignal(signal:any,dev:any){
 
   
    var signalNumricvalue = parseInt(signal);

    if(signalNumricvalue == 0) {
      this.gsmURL = "../../assets/images/tower/tower0.png";
      this.gsmStatus = "Signal strength" + " "+ signal;
      return true;
    } else if ((signalNumricvalue > 0)&&(signalNumricvalue<5)) {
      this.gsmURL = "../../assets/images/tower/tower5.png";
      this.gsmStatus = "Signal strength" + " "+ signal;
      return true;
    } else if ((signalNumricvalue >= 5)&&(signalNumricvalue<10)) {
      this.gsmURL = "../../assets/images/tower/tower10.png";
      this.gsmStatus = "Signal strength" + " "+ signal;
      return true;
    } else if ((parseFloat(signal) >= 10)&&(parseFloat(signal)<15)) {
      this.gsmURL = "../../assets/images/tower/tower15.png";
      this.gsmStatus = "Signal strength" + " "+ signal;
      return true;
    } else if ((signalNumricvalue >= 15)&&(signalNumricvalue<20)) {
      this.gsmURL = "../../assets/images/tower/tower20.png";
      this.gsmStatus = "Signal strength" + " "+ signal;
      return true;
    }
    else if ((signalNumricvalue >= 20)&&(signalNumricvalue<25)) {
      this.gsmURL = "../../assets/images/tower/tower25.png";
      this.gsmStatus = "Signal strength" + " "+ signal;
      return true;
    }
    else if (signalNumricvalue >= 25){
      this.gsmURL = "../../assets/images/tower/tower30.png";
      this.gsmStatus = "Signal strength" + " "+ signal;
      return true;
    }else{
      this.gsmURL = "../../assets/images/tower/tower7.png";
      this.gsmStatus = "No Signal";
      return true;
    }

  }

  gpsStatus(gTrack) {
    if (!gTrack) {
      this.gpsImg = "../../assets/image/no_gps.png";
      this.gStatus = "GPS NOT SUPPORTED"
      return true;
    } else if (gTrack == "1") {
      this.gpsImg = "../../assets/image/gpsOn.png";
      this.gStatus = "GPS ON"
      return true;
    } else if (gTrack == "0") {
      this.gpsImg = "../../assets/image/gps_off.png";
      this.gStatus = "GPS OFF"
      return true;
    } else {
      return false;
    }

  }

  gpsACStatus(ACtrack) {
    if (!ACtrack) {
      // grey
      this.ACImg = "../../assets/image/acGrey.png";
      this.aStatus = "AC NOT SUPPORTED"
      return true;
    } else if (ACtrack == "1") {
      // green
      this.ACImg = "../../assets/image/acGreen.png";
      this.aStatus = "AC ON"
      return true;
    } else if (ACtrack == "0") {
      // red
      this.ACImg = "../../assets/image/acRed.png";
      this.aStatus = "AC OFF"
      return true;
    } else {
      return false;
    }

  }


  iconCheck(status, iconType) {
  
    var devStatus = status.split(" ");
   
    if ((iconType == 'car') && (devStatus[0] == "OUT")) {
      this.devIcon = "../../assets/image/outOfReach_car.png";
      return this.devIcon;
    } else if ((iconType == 'car') && (devStatus[0] == "RUNNING")) {
      this.devIcon = "../../assets/image/running_car.png";
      return this.devIcon;
    } else if ((iconType == 'car') && (devStatus[0] == "STOPPED")) {
      this.devIcon = "../../assets/image/stopped_car.png";
      return this.devIcon;
    } else if ((iconType == 'car') && (devStatus[0] == "IDLING")) {
      this.devIcon = "../../assets/image/idle_car.png";
      return this.devIcon;
    } else if ((iconType == 'car') && (devStatus[0] == "NO")) {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } 
    else if ((iconType == 'bike') && (devStatus[0] == "OUT")) {
      this.devIcon = "../../assets/image/outOfReach_bike.png";
      return this.devIcon;
    } else if ((iconType == 'bike') && (devStatus[0] == "RUNNING")) {
      this.devIcon = "../../assets/image/running_bike.png";
      return this.devIcon;
    } else if ((iconType == 'bike') && (devStatus[0] == "STOPPED")) {
      this.devIcon = "../../assets/image/stopped_bike.png";
      return this.devIcon;
    } else if ((iconType == 'bike') && (devStatus[0] == "IDLING")) {
      this.devIcon = "../../assets/image/idle_bike.png";
      return this.devIcon;
      // }
    }  else if ((iconType == 'bike') && (devStatus[0] == "NO")) {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else if ((iconType == 'bus') && (devStatus[0] == "OUT")) {
      this.devIcon = "../../assets/image/bus_out.png";
      return this.devIcon;
    } else if ((iconType == 'bus') && (devStatus[0] == "RUNNING")) {
      this.devIcon = "../../assets/image/bus_running.png";
      return this.devIcon;
    } else if ((iconType == 'bus') && (devStatus[0] == "STOPPED")) {
      this.devIcon = "../../assets/image/bus_stop.png";
      return this.devIcon;
    } else if ((iconType == 'bus') && (devStatus[0] == "IDLING")) {
      this.devIcon = "../../assets/image/idle_bus.png";
      return this.devIcon;
    } else if ((iconType == 'bus') && (devStatus[0] == "NO")) {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } 
    else if ((iconType == 'truck') && (devStatus[0] == "OUT")) {
      this.devIcon = "../../assets/image/our_truck.png";
      return this.devIcon;
    } else if ((iconType == 'truck') && (devStatus[0] == "RUNNING")) {
      this.devIcon = "../../assets/image/running_truck.png";
      return this.devIcon;
    } else if ((iconType == 'truck') && (devStatus[0] == "STOPPED")) {
      this.devIcon = "../../assets/image/stopped_truck.png";
      return this.devIcon;
    } else if ((iconType == 'truck') && (devStatus[0] == "IDLING")) {
      this.devIcon = "../../assets/image/idle_truck.png";
      return this.devIcon;
    } else if ((iconType == 'truck') && (devStatus[0] == "NO")) {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } 
    else if ((iconType == 'tractor') && (devStatus[0] == "OUT")) {
      this.devIcon = "../../assets/image/tractor_blue.png";
      return this.devIcon;
    } else if ((iconType == 'tractor') && (devStatus[0] == "RUNNING")) {
      this.devIcon = "../../assets/image/tractor_green.png";
      return this.devIcon;
    } else if ((iconType == 'tractor') && (devStatus[0] == "STOPPED")) {
      this.devIcon = "../../assets/image/tractor_red.png";
      return this.devIcon;
    } else if ((iconType == 'tractor') && (devStatus[0] == "IDLING")) {
      this.devIcon = "../../assets/image/tractor_yellow.png";
      return this.devIcon;
    }
    else if ((iconType == 'tractor') && (devStatus[0] == "NO")) {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } 
    else if((!iconType)&&(devStatus[0] == "OUT")){
      this.devIcon = "../../assets/image/outOfReach_car.png";
      return this.devIcon;
    } else if((!iconType)&&(devStatus[0] == "RUNNING")){
      this.devIcon = "../../assets/image/running_car.png";
      return this.devIcon;
    }else if((!iconType)&&(devStatus[0] == "STOPPED")){
      this.devIcon = "../../assets/image/stopped_car.png";
      return this.devIcon;
    }else if((!iconType)&&(devStatus[0] == "IDLING")){
      this.devIcon = "../../assets/image/idle_car.png";
      return this.devIcon;
    }else if ((iconType == 'user') && (devStatus[0] == "OUT")) {
      this.devIcon = "../../assets/image/user_b.png";
      return this.devIcon;
    } else if ((iconType == 'user') && (devStatus[0] == "RUNNING")) {
      this.devIcon = "../../assets/image/user_g.png";
      return this.devIcon;
    } else if ((iconType == 'user') && (devStatus[0] == "STOPPED")) {
      this.devIcon = "../../assets/image/user_r.png";
      return this.devIcon;
    } else if ((iconType == 'user') && (devStatus[0] == "IDLING")) {
      this.devIcon = "../../assets/image/user_y.png";
      return this.devIcon;
      
    }else if ((iconType == 'jcb') && (devStatus[0] == "OUT")) {
      this.devIcon = "../../assets/image/jcb_blue.png";
      return this.devIcon;
    } else if ((iconType == 'jcb') && (devStatus[0] == "RUNNING")) {
      
      this.devIcon = "../../assets/image/jcb_green.png";
      return this.devIcon;
    } else if ((iconType == 'jcb') && (devStatus[0] == "STOPPED")) {     
      this.devIcon = "../../assets/image/jcb_red.png";
      return this.devIcon;
    } else if ((iconType == 'jcb') && (devStatus[0] == "IDLING")) {     
      this.devIcon = "../../assets/image/jcb_yellow.png";
      return this.devIcon;      
    }
    else if ((iconType == 'ambulance') && (devStatus[0] == "OUT")) {
      
      this.devIcon = "../../assets/images/liveTrackIcons/ambulance_b.png";
      return this.devIcon;
    } else if ((iconType == 'ambulance') && (devStatus[0] == "RUNNING")) {
      
      this.devIcon = "../../assets/images/liveTrackIcons/ambulance_g.png";
      return this.devIcon;  
    } else if ((iconType == 'ambulance') && (devStatus[0] == "STOPPED")) {     
      this.devIcon = "../../assets/images/liveTrackIcons/ambulance_r.png";
      return this.devIcon;
    } else if ((iconType == 'ambulance') && (devStatus[0] == "IDLING")) {     
      this.devIcon = "../../assets/images/liveTrackIcons/ambulance_y.png";
      return this.devIcon;      
    } 
    else{
      this.devIcon = "../../assets/image/noIcon.png";
      return this.devIcon
    }

  }


  myInput: any;

  //sorting
  key: string = 'Device_Name'; //set default
  reverse: boolean = false;
  sort(key) {
    // console.log(key);
    this.key = key;
    this.reverse = !this.reverse;
  }

  //initializing p to one
  page: number = 1;



  it: number;
  timeIntervalRefresh() {
    // var that=this;
    clearInterval(this.interval);

    this.it = (1000 * this.setTimeOut.value);

    this.interval = setInterval(() => {
      this.sidebarData(10);
      this.getGraphFunction();
      this.getNotificationCount()
    }, this.it);


  }


  refreshFUnction(ev) {


    this.setTimeOut.value = ev;

    this.timeIntervalRefresh();

  }



  // refreshData(){

  //   this.sidebarData(); // simply signal for the service to update its data stream
  // }

  locationAddress: any;
  getAddress(device) {
    var ds = device.status;
    var exStatus = ds.slice(0,7);
    if(exStatus === 'Expired'){
      // swal({
      //   title: 'Expired',
      //   text: "Renew Your subscription for uninterrupted service",
      //   type: 'warning',
      //   showCancelButton: false,
      //   confirmButtonColor: '#3085d6',
    
      //   confirmButtonText: 'ok'
      // })
    }else{
      this.lattitude = device.last_location?device.last_location.lat:0;
      this.longitude = device.last_location?device.last_location.long:0;
      var latlng_1 =
      {
        "lat": device.last_location?device.last_location.lat:0,
        "long": device.last_location?device.last_location.long:0
      }
      this.contactService.getAddressByApi(latlng_1).subscribe(res=>{
        // console.log('addressresponse=>',res);
        if(res.message == "Address not found in databse"){
          this.addressConversionBygoogleAPI(device);
        }else{
          device.locationAddress = res.address;
          device['pen'] = true;
         
        }
      })
    }
 
   
  }



  addressConversionBygoogleAPI(device){
    var outerThis = this;
    if (device.last_location == undefined) {
      this.lattitude = null;
      this.longitude = null;
    } else {

      this.lattitude = device.last_location.lat;
      this.longitude = device.last_location.long;
    }


    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(this.lattitude, this.longitude);

    var request = {
      latLng: latlng,
     
    };



    geocoder.geocode(request, function (data, status) {
      console.log('request',data);
   
      if (status == google.maps.GeocoderStatus.OK) {
        if (data[0] != null) {
          console.log('request',request);
          outerThis.address_show = data[0].formatted_address;
          device.locationAddress = outerThis.address_show;
          device['pen'] = true;
          outerThis.saveAddress(outerThis.lattitude,outerThis.longitude,outerThis.address_show);

        } else {

          device.locationAddress = "No address available";

        }
      }
      else {

        outerThis.address_show = outerThis.lattitude + ", " + outerThis.longitude;
        device.locationAddress = outerThis.address_show;
        device['pen'] = true;

      }

    })

  }

  translateAddressToHindi(device){
    console.log("Device",device);
    // translation
    var index=this.deviceData.indexOf(device);
    console.log("herk",this.deviceData.indexOf(device))
    this.contactService.addressTranslationInHindi({text:device.locationAddress}).subscribe(res=>{
      this.deviceData[index].locationAddress=res.translation;
      console.log(res);
    })
    

  }


  saveAddress(lat,lng,address){
    var addressObj = {"lat":lat,
    "long":lng,
    "address":address
  }
    this.contactService.saveAdd(addressObj).subscribe(res=>{
      console.log(res);
    },err=>{
      console.log("couldn't save address");
    })

  }



  updateAddress(dev){
    console.log(dev);
   
    let dialogRef = this.dialog.open(ManualAddressComponent, {
      width: '600px',
      data: dev
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result == "success") {
        console.log(result);
      }

      else if (result == "cancel") {
        console.log(result);  
      }
    });

  }


  skip: number = 0;
  limit: number = 10;
  firstcall: boolean = false;
  lastcall: boolean = true;
  next() {
    this.lastcall = false;
    this.skip += 1;
    // console.log("skip=>",this.skip);
    if(this.filterId== 'i'){
      this.getDeviceBYfilterIdle(10);
     
    }else if(this.filterId == 'r'){
      this.getDeviceBYfilter(10);
     
    }else if(this.filterId == 's'){
      this.getDeviceBYfilterStop(10);
      
    }else if(this.filterId == 'm'){
      this.getDeviceBYfilterMain(10);
     
    }else if(this.filterId == 'our'){
      this.getDeviceBYfilterOUR(10);   
    }else if(this.filterId == 'nogpsfix'){
      this.getDeviceBYfilterNOGPS(10);
    }   else if(this.filterId == 'av'){
        this.getAddedVehList(this.keyIdentifier);  
      }
      else if(this.filterId == 'ev'){
        this.getExpiredVehList(this.keyIdentifier);
      }
      else if(this.filterId == 'rv'){
          this.renewedVehList(this.keyIdentifier);
      }else{
      this.sidebarData(10);
   
    }

    
  }
  pre() {
    // console.log(this.skip)
    if (this.skip > 0) {
      this.skip -= 1;
      this.lastcall = false;
      if(this.filterId== 'i'){
        this.getDeviceBYfilterIdle(10);
       
      }else if(this.filterId == 'r'){
        this.getDeviceBYfilter(10);
      
      }else if(this.filterId == 's'){
        this.getDeviceBYfilterStop(10);
      
      }else if(this.filterId == 'm'){
        this.getDeviceBYfilterMain(10);
       
      }else if(this.filterId == 'our'){
        this.getDeviceBYfilterOUR(10);
      }else if(this.filterId == 'nogpsfix'){
        this.getDeviceBYfilterNOGPS(10);
      }
      else if(this.filterId == 'av'){
        this.getAddedVehList(this.keyIdentifier);
       
      }
      else if(this.filterId == 'ev'){
        this.getExpiredVehList(this.keyIdentifier);
     
      }
      else if(this.filterId == 'rv'){
          this.renewedVehList(this.keyIdentifier);
      }else{
        this.sidebarData(10);
        
      }
    } else {
      this.lastcall = true;
      this.firstcall = false;
    }

  }


  searchFilter(text: string,id) {
    this.modelChanged.next(text);

  }


  getfuel(device,ind){
      // console.log(ind);
      // console.log(device);
      // debugger;
     var show_val = '';
     if(this.fuelflag == 'l'){
      if((device.currentFuel == undefined)||(device.currentFuel == NaN)||(device.currentFuel == null)){
        show_val = '0';
        return show_val;
      }else{
         show_val = device.currentFuel
        return show_val;
      }
     }
     if(this.fuelflag == 'p'){
      if((device.fuel_percent == undefined)||(device.fuel_percent == NaN)||(device.fuel_percent == null)){
        show_val = '0';
        return show_val;
      }else{
         show_val = device.fuel_percent;
        return show_val;
      }
     }
   
  }


  gettemp(t){
    if(t){
      return (parseFloat(t)/10).toFixed(2);
    }else{
      return 0 ;
    }
  }

  public ngOnDestroy() {
    localStorage.setItem('refreshInterval', JSON.stringify(this.setTimeOut.value));
    if(this.final){
      for (var e = 0; e < this.final.length; e++) {
        this.socket_Ing.removeAllListeners(this.final[e])
      }
    }
    clearInterval(this.interval);
  }

  removeGroup() {
    this.groupId = undefined;
    this.groupName = undefined;
    this.getGraphFunction();
    this.sidebarData(10);
  }



  // =============================new Dashboard =======================================================
   
  DeviceSummaryArr = [
    {status : "TOTAL VEHICLES" , total : this.total_vech?this.total_vech:0  , icon : "../../assets/image/totalVehicle.png"},
    {status : "RUNNING", total : this.Running?this.Running:0 , icon : "../../assets/image/totalVehicle.png"},
    {status : "STOPPED" , total : this.off_vech?this.off_vech:0 , icon : "../../assets/image/totalVehicle.png"},
    {status : "IDLE" , total : this.idle_vech?this.idle_vech:0  , icon : "../../assets/image/totalVehicle.png"},
    {status : "OUT OF REACH" , total : this.OutOfReach?this.OutOfReach : 0 , icon : "../../assets/image/totalVehicle.png"},
    {status : "EXPIRED" , total : this.expire_status?this.expire_status : 0 , icon : "../../assets/image/totalVehicle.png"},
    {status : "NO DATA" , total : this.no_data?this.no_data : 0 , icon : "../../assets/image/totalVehicle.png"},
  ]


    devicebystatus(devstatus){
      if(devstatus == 'TOTAL VEHICLES'){
        this.sidebarData(0);
      }

      if(devstatus == 'RUNNING'){
        this.getDeviceBYfilter(1);
      }

      if(devstatus == 'STOPPED'){
        this.getDeviceBYfilterStop(3)
      }

      if(devstatus == 'IDLE'){
        this.getDeviceBYfilterIdle(2);
      }

      if(devstatus == 'OUT OF REACH'){
        this.getDeviceBYfilterOUR(5);
      }

      if(devstatus == 'NO GPS'){
        this.getDeviceBYfilterNOGPS(6);
      }
      if(devstatus == 'EXPIRED'){
        this.getDeviceBYfilterEXPIRED(7);
      }
      if (devstatus == 'NO DATA') {
      this.getDeviceBYfilterNoData(8)
      }
    }

    vehicleUtilizationGraph() {
    var that = this ;
    var tOut = setTimeout(function(){
      var canvas = <HTMLCanvasElement>document.getElementById("deviceBarChart");
    
      var ctx = canvas.getContext("2d");
    //   clearTimeout(tOut);
    // },2000)
  

  
    var role = ''
    var userid = that.useridd ;
    if(that.superAdmin === true){
      role = 'supAdmin' ; 
    }else if(that.custtype === true){
      role = 'Dealer'
    }else{
      role = 'User'
    }

    var barChartData = {
      labels: [
        "Today",
        "Week",
        "Month"
      ],
      datasets: [
        {
          label: "Running",
          backgroundColor: "#86AC41",
          borderColor: "white",
          borderWidth: 1,
          data: [0,0,0]
        },
        {
          label: "Out of Reach",
          backgroundColor: "#4897D8",
          borderColor: "white",
          borderWidth: 1,
          data: [0,0,0]
        },
        {
          label: "Idle",
          backgroundColor: "#F5BE41",
          borderColor: "white",
          borderWidth: 1,
          data: [0,0,0]
        },
        {
          label: "Stopped",
          backgroundColor: "#CB0000",
          borderColor: "white",
          borderWidth: 1,
          data: [0,0,0]
        }
      ]
    };
    
    var chartOptions = {
      responsive: true,
      maintainAspectRatio: false,
      title: {
        display: true,
        fontSize:14,
        text: 'Vehicle Utilization'
    },
      legend: {
        position: "top"
      },
   
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
            max: 100,
            min: 0
          }
        }]
      }
    }
    
  that.deviceBarChart =  new Chart(ctx,{
    "type":"bar",
    "data":barChartData, 
    "options":chartOptions
  })

    that.contactService.vehicleUtilization(role,userid).subscribe(res=>{
      console.log('resresresresresresres=>',res);
      var bargraph = res;
      console.log('bargraph',bargraph.length);
  
      if((bargraph.length != 0)&&(bargraph.length != undefined)){
        var varGraphObject = bargraph;  
      
        for(let bg in varGraphObject){
       
          var runningArr = [
            (varGraphObject[0]['Daily']['Running'] != undefined)?varGraphObject[0]['Daily']['Running']:0,
            (varGraphObject[1]['Weekly']['Running']!=undefined)?varGraphObject[1]['Weekly']['Running']:0,
            (varGraphObject[2]['Monthly']['Running'] != undefined)?varGraphObject[2]['Monthly']['Running']:0
          ] ; 
          var IdleArr = [
            (varGraphObject[0]['Daily']['Idle'] != undefined)?varGraphObject[0]['Daily']['Idle'] :0,
            (varGraphObject[1]['Weekly']['Idle'] != undefined)?varGraphObject[1]['Weekly']['Idle']:0,
            (varGraphObject[2]['Monthly']['Idle'] != undefined)?varGraphObject[2]['Monthly']['Idle'] :0
          ] ;
          var OFRArr = [
            (varGraphObject[0]['Daily']['OFR'] != undefined)?varGraphObject[0]['Daily']['OFR']:0,
            (varGraphObject[1]['Weekly']['OFR'] != undefined)?varGraphObject[1]['Weekly']['OFR']:0,
            (varGraphObject[2]['Monthly']['OFR'] != undefined)?varGraphObject[2]['Monthly']['OFR']:0
          ] ;
          var StopArr = [
            (varGraphObject[0]['Daily']['Stop'] != undefined)?varGraphObject[0]['Daily']['Stop']:0,
            (varGraphObject[1]['Weekly']['Stop'] != undefined)?varGraphObject[1]['Weekly']['Stop'] :0,
            (varGraphObject[2]['Monthly']['Stop'] != undefined)?varGraphObject[2]['Monthly']['Stop']:0
          ] ;
        }
      }
  
       barChartData = {
        labels: [
          "Today",
          "Week",
          "Month"
        ],
        datasets: [
          {
            label: "Running",
            backgroundColor: "#86AC41",
            borderColor: "white",
            borderWidth: 1,
            data: runningArr
          },
          {
            label: "Out of Reach",
            backgroundColor: "#4897D8",
            borderColor: "white",
            borderWidth: 1,
            data: OFRArr
          },
          {
            label: "Idle",
            backgroundColor: "#F5BE41",
            borderColor: "white",
            borderWidth: 1,
            data: IdleArr
          },
          {
            label: "Stopped",
            backgroundColor: "#CB0000",
            borderColor: "white",
            borderWidth: 1,
            data: StopArr
          }
        ]
      };
      
     
    that.deviceBarChart =  new Chart(ctx,{
      "type":"bar",
      "data":barChartData, 
      "options":chartOptions
    })
    },err=>{
      console.log(err);
    })

    clearTimeout(tOut);
  },3000)

  }


  expenseChart(){
    var that =this;
    var tOut2 = setTimeout(function(){
      var userId = that.useridd ; 
      var canvas_2 = <HTMLCanvasElement>document.getElementById("deviceExpense");
      var ctx_2 = canvas_2.getContext("2d");
      var daugnoutChart_1 = {
        datasets: [{
          data: [0,0,0,0,0],
          backgroundColor:['#86AC41', '#CB0000', '#F5BE41','#4897D8','#5B7065'],
        }],
    
        labels: [
          'Service',
          'Oil Changed',
          'Maintenance',
          'Tyres',
          'Others'
        ]
      };
  
      var optionDonought = {
        responsive: true,
        maintainAspectRatio: false,
        title: {
          display: true,
          fontSize:14,
          text: 'Expense'
      }
      };
  
        
      that.devicePiChart_1 = new Chart(ctx_2, {
        type: 'doughnut',
        data: daugnoutChart_1,
        options: optionDonought
      });
      that.contactService.getExpenseGrapgData(userId).subscribe(res=>{
        console.log('resresresresresresres',res);
      
        var expenseData = res ; 
        var expData = [0,0,0,0,0];
        var expLevel = ['Service',
        'Oil Changed',
        'Maintenance',
        'Tyres',
        'Others']
        if(expenseData.length != 0){
          expData=[];
          expLevel =[];
          for( var i=0;i < expenseData.length;i++){     
            expData.push(expenseData[i].amount);
            expLevel.push(expenseData[i]._id)
  
          }
       
        }
        console.log('expDataexpDataexpDataexpDataexpData',expData);
     daugnoutChart_1 = {
          datasets: [{
            data:expData,
            backgroundColor:['#86AC41', '#CB0000', '#F5BE41','#4897D8','#5B7065'],
          }],
          labels: expLevel
        };
      
        that.devicePiChart_1 = new Chart(ctx_2, {
          type: 'doughnut',
          data: daugnoutChart_1,
          options: optionDonought
        });
      },err=>{
        console.log(err);
      })
       clearTimeout(tOut2);
    },3000)

  }
  NoGPS :any;
  utilisationChart(){
    var that = this; 
    $( document ).ready(function() {
      var canvas_1 = <HTMLCanvasElement>document.getElementById("utilisationChart");
      var ctx_1 = canvas_1.getContext("2d");
      var daugnoutChart = {
        datasets: [{
          data: [
            that.Running?that.Running:0,
            that.off_vech?that.off_vech:0,
            that.idle_vech?that.idle_vech:0,
            that.OutOfReach?that.OutOfReach : 0,
            that.NoGPS?that.NoGPS : 0
          ],
          backgroundColor:['#86AC41', '#CB0000', '#F5BE41','#4897D8','#5B7065'],
        }],
    
      
        labels: [
         'RUNNING',
          'STOPPED',
          'IDLE',
          'OUT OF REACH',
          'NO GPS' 
        ]
      };
    
        var optionDonought_1 = {
          responsive: true,
          maintainAspectRatio: false,
          title: {
            display: true,    
            fontSize:14,
            text: 'Vehicle Current Status'
        }
        };
    
        that.devicePiChart = new Chart(ctx_1, {
          type: 'doughnut',
          data: daugnoutChart,
          options: optionDonought_1
        });
  });
    
  }


  reminderVal : any;
  reminderType = [{
      value : "7daysL",
      viewValue : "Last 7 days"
    },{
      value : "15daysL",
      viewValue : "Last 15 days"
    },{
      value : "30daysL",
      viewValue : "Last 30 days"
    },{
      value : "7daysN",
      viewValue : "Next 7 days"
    },{
      value : "15daysN",
      viewValue : "Next 15 days"
    },{
      value : "30daysN",
      viewValue : "Next 30 days"
    }];
    reminderrr:any;
    vehicleReminder(){
      var Uid = this.useridd;
      this.reminderrr = [];
      this.contactService.getVehicleReminder(Uid).subscribe(res=>{
        console.log('this.reminderVal',this.reminderVal);
        this.reminderrr = res[0];
        var notifString = '';
        this.notifArr = [];
        if(this.reminderVal == '7daysL'){
          this.reminderrr = res[0]['last_seven'];
          if(this.reminderrr.length != 0){
            let devName = '';
            let reminderType = '';
            let reminderDate = '';
            for(var i=0;i<this.reminderrr.length;i++){
              var rd = moment(this.reminderrr[i].reminder_date).format('lll');;
              notifString = 'Reminder for Vehicle' + ' ' + this.reminderrr[i].device.Device_Name + ' ' +'for' +' '+ this.reminderrr[i].reminder_type +' ' + 'on' +' '+ rd;
              this.notifArr.push(notifString);
              console.log('notifArr',this.notifArr);
            }
          }
     
        }
        if(this.reminderVal == '15daysL'){
          this.reminderrr = res[1]['last_fifteen'];
          if(this.reminderrr.length != 0){
            let devName = '';
            let reminderType  = '';
            let reminderDate = '';
            for(var i=0;i<this.reminderrr.length;i++){
              var rd = moment(this.reminderrr[i].reminder_date).format('lll');;
              notifString = 'Reminder for Vehicle' + ' ' + this.reminderrr[i].device.Device_Name + ' ' +'for' +' '+ this.reminderrr[i].reminder_type +' ' + 'on' +' '+ rd;
              this.notifArr.push(notifString);
              console.log('notifArr',this.notifArr);
            }
          }
        }

        if(this.reminderVal == '30daysL'){
          this.reminderrr = res[2]['last_thirty']; 
          if(this.reminderrr.length != 0){
            let devName = '';
            let reminderType = '';
            let reminderDate = '';
            for(var i=0;i<this.reminderrr.length;i++){
              var rd = moment(this.reminderrr[i].reminder_date).format('lll');;
              notifString = 'Reminder for Vehicle' + ' ' + this.reminderrr[i].device.Device_Name + ' ' +'for' +' '+ this.reminderrr[i].reminder_type +' ' + 'on' +' '+ rd;
              this.notifArr.push(notifString);
              console.log('notifArr',this.notifArr);
            }
          }
        }
        if(this.reminderVal == '7daysN'){
          this.reminderrr = res[3]['next_seven']; 
          if(this.reminderrr.length != 0){
            let devName = '';
            let reminderType = '';
            let reminderDate = '';
            for(var i=0;i<this.reminderrr.length;i++){
              var rd = moment(this.reminderrr[i].reminder_date).format('lll');;
              notifString = 'Reminder for Vehicle' + ' ' + this.reminderrr[i].device.Device_Name + ' ' +'for' +' '+ this.reminderrr[i].reminder_type +' ' + 'on' +' '+ rd;
              this.notifArr.push(notifString);
              console.log('notifArr',this.notifArr);
            }
          }
        }   if(this.reminderVal == '15daysN'){
          this.reminderrr = res[4]['next_fifteen']; 
          if(this.reminderrr.length != 0){
            let devName = '';
            let reminderType = '';
            let reminderDate = '';
            for(var i=0;i<this.reminderrr.length;i++){
              var rd = moment(this.reminderrr[i].reminder_date).format('lll');;
              notifString = 'Reminder for Vehicle' + ' ' + this.reminderrr[i].device.Device_Name + ' ' +'for' +' '+ this.reminderrr[i].reminder_type +' ' + 'on' +' '+ rd;
              this.notifArr.push(notifString);
              console.log('notifArr',this.notifArr);
            }
          }
        }   if(this.reminderVal == '30daysN'){
          this.reminderrr = res[5]['next_thirty']; 
          if(this.reminderrr.length != 0){
            let devName = '';
            let reminderType = '';
            let reminderDate = '';
            for(var i=0;i<this.reminderrr.length;i++){
              var rd = moment(this.reminderrr[i].reminder_date).format('lll');;
              notifString = 'Reminder for Vehicle' + ' ' + this.reminderrr[i].device.Device_Name + ' ' +'for' +' '+ this.reminderrr[i].reminder_type +' ' + 'on' +' '+ rd;
              this.notifArr.push(notifString);
              console.log('notifArr',this.notifArr);
            }
          }
        }

      },err=>{
        console.log(err);
      })
    }

    getreminderevent(ev){
      console.log(ev);
    
       this.reminderVal =   ev.value;
       this.vehicleReminder();


    }

    showSharedDevice(deviceObj){
      let dialogRef = this.dialog.open(SharedDevicesComponent, {
        width: '600px',
        data: deviceObj
      });
  
      dialogRef.afterClosed().subscribe(result => {
        if (result == "success") {
          console.log(result);
        }

        else if (result == "cancel") {
          console.log(result);  
        }
      });
    

    }
   
    addedDeviceVal:any;
    expiredDeviceVal:any;
    totalExpiredCount=[{'key' : 'Today','value' : 0},{'key' : 'Week','value' : 0},{'key' : 'Month','value' : 0}];
    totalRenewedCount=[{'key' : 'Today','value' : 0},{'key' : 'Week','value' : 0},{'key' : 'Month','value' : 0}];
    totalCount = [{'key' : 'Today','value' : 0},{'key' : 'Week','value' : 0},{'key' : 'Month','value' : 0}];
    billingDetailArr = [{'key' : 'Paid','value' : 0},{'key' : 'Pending','value' : 0}];
    VehicleAdded = ['Today','Last Week','Last Month'];
    getDeviceCount($event,id){
      console.log($event);
      console.log(id);
    }


    getTotalDeviceCount(){
      var role = '';
        if(this.superAdmin === true){
          role =  'supAdmin' ;

        }
        if(this.custtype === true){
          role =  'Dealer' ;

        }
      
     
      
      // var role = 'supAdmin';
      var user_id = this.useridd; 
     
      this.contactService.getDeviceCount(role,user_id).subscribe(res=>{
        this.totalCount = [{'key' : 'Today','value' : 0},{'key' : 'Week','value' : 0},{'key' : 'Month','value' : 0}];
        this.totalCount = [{'key' : 'Today','value' : res[0].today?res[0].today:0},{'key' : 'Week','value' : res[1].week?res[1].week:0},{'key' : 'Month','value' : res[2]?res[2].month:0}];
        console.log(this.totalCount);


      },err=>{
        console.log(err); 
      })
    }


    getTotalExpiredDeviceCount(){
      // http://localhost:3000/gps/DeviceExpiredCount?role=supAdmin&id=59cbbdbe508f164aa2fef3d8   

      var role1 = '';
      if(this.superAdmin === true){
        role1 =  'supAdmin' ;

      }
      if(this.custtype === true){
        role1 =  'Dealer' ;

      }
    
     
      // var role1 = 'supAdmin';
      var user_id1 = this.useridd; 

      this.contactService.getExpiredDeviceCount(role1,user_id1).subscribe(res=>{
        this.totalExpiredCount = [{'key' : 'Today','value' : 0},{'key' : 'Week','value' : 0},{'key' : 'Month','value' : 0}];
        this.totalExpiredCount = [{'key' : 'Today','value' : res[0].today?res[0].today:0},{'key' : 'Week','value' : res[1].week?res[1].week:0},{'key' : 'Month','value' : res[2]?res[2].month:0}];
        console.log(this.totalExpiredCount);


      },err=>{

      })
    }


    getTotalRenewedDeviceCount(){
      // http://localhost:3000/gps/DeviceExpiredCount?role=supAdmin&id=59cbbdbe508f164aa2fef3d8   

      var role1 = '';
      if(this.superAdmin === true){
        role1 =  'supAdmin' ;

      }
      if(this.custtype === true){
        role1 =  'Dealer' ;

      }
    
     
      // var role1 = 'supAdmin';
      var user_id1 = this.useridd; 

      this.contactService.getRenewDeviceCount(role1,user_id1).subscribe(res=>{
        this.totalRenewedCount = [{'key' : 'Today','value' : 0},{'key' : 'Week','value' : 0},{'key' : 'Month','value' : 0}];
        this.totalRenewedCount = [{'key' : 'Today','value' : res[0].today?res[0].today:0},{'key' : 'Week','value' : res[1].week?res[1].week:0},{'key' : 'Month','value' : res[2]?res[2].month:0}];
        console.log(this.totalRenewedCount);


      },err=>{

      })
    }


    // demoVideos(){
    //   let dialogRef = this.dialog.open(DemoVideosComponent, {
    //     // width: '903px',
    //     // data: { Type: type, dataset: datasets }
    //     panelClass: 'custom-dialog-container'
    //   });
  
    //   dialogRef.afterClosed().subscribe(result => {
    //     if (result == "OKK") {
  
    //     }
    //     else if (result == "No_Dev") {
  
  
    //     }
    //   });


    // }


    getApiKey(){
      // debugger;
     var api_key = 'AIzaSyA_ycttLXPMfCSSNAfPOsaENPQ85i17lPU';
     var apiIdentifier = localStorage.getItem('apiIdentifier');
     if(apiIdentifier == null){
       console.log("Inside AppIdentifier");
      this.contactService.getgoogleApi(this.useridd).subscribe(res=>{
        if(res.message != "api key not found"){
         api_key = res.api_key;      
          // var script = document.createElement('script');
          // script.setAttribute("type", "text/javascript");
          // script.setAttribute("src", "https://maps.google.com/maps/api/js?libraries=geometry,places,drawing&key="+ api_key);
          // document.getElementsByTagName("head")[0].appendChild(script);
          document.getElementById('mapApi').setAttribute("src", "https://maps.google.com/maps/api/js?libraries=geometry,places,drawing&key=" + api_key);
          localStorage.setItem('apiIdentifier',api_key);  
        }else{
      
          // var script = document.createElement('script');
          // script.setAttribute("type", "text/javascript");
          // script.setAttribute("src", "https://maps.google.com/maps/api/js?libraries=geometry,places,drawing&key=AIzaSyA_ycttLXPMfCSSNAfPOsaENPQ85i17lPU");
          // document.getElementsByTagName("head")[0].appendChild(script);
          document.getElementById('mapApi').setAttribute("src", "https://maps.google.com/maps/api/js?libraries=geometry,places,drawing&key="+api_key);
          localStorage.setItem('apiIdentifier',api_key);
        }
    },err=>{
      // var script = document.createElement('script');
      // script.setAttribute("type", "text/javascript");
      // script.setAttribute("src", "https://maps.google.com/maps/api/js?libraries=geometry,places,drawing&key=AIzaSyA_ycttLXPMfCSSNAfPOsaENPQ85i17lPU");
      // document.getElementsByTagName("head")[0].appendChild(script);
      document.getElementById('mapApi').setAttribute("src", "https://maps.google.com/maps/api/js?libraries=geometry,places,drawing&key="+api_key);
      localStorage.setItem('apiIdentifier',api_key);
    })

     }else{
       console.log(apiIdentifier);
      var aCount =  localStorage.getItem('apiCOunt');
       if(aCount != '1'){
        // var script = document.createElement('script');
        // script.setAttribute("type", "text/javascript");
        document.getElementById('mapApi').setAttribute("src", "https://maps.google.com/maps/api/js?libraries=geometry,places,drawing&key=" + apiIdentifier);
        // document.getElementsByTagName("head")[0].appendChild(script);
        localStorage.setItem('apiCOunt','1');
       }
     }
    }
    
    keyIdentifier:any;
    getAddedVehList(key){
  
     this.filterId = 'av';
      if(key === 'Today'){
        key='today';
        this.keyIdentifier = key;
      }
      if(key === 'Week'){
        key='week';
        this.keyIdentifier = key;
      }
      if(key === 'Month'){
        key='month';
        this.keyIdentifier = key;
      }
   
      var role = '';
      if(this.superAdmin === true){  role =  'supAdmin' ;}
      if(this.custtype === true){role =  'Dealer' ;}
      var user_id = this.useridd; 
      this.contactService.getDeviceCount1(role,user_id,key,this.skip,this.limit).subscribe(res=>{
        console.log('added deviceList',res);
        this.filtes = res;
        this.abc(this.filtes);
      })
    }
    getExpiredVehList(key){
      this.filterId = 'ev';
     console.log(this.skip);
      if(key === 'Today'){
        key='today';
        this.keyIdentifier = key;
      }
      if(key === 'Week'){
        key='week';
        this.keyIdentifier = key;
      }
      if(key === 'Month'){
        key='month';
        this.keyIdentifier = key;
      }    
      var role = '';
      if(this.superAdmin === true){  role =  'supAdmin' ;}
      if(this.custtype === true){role =  'Dealer' ;}
      var user_id = this.useridd; 
      this.contactService.getExpiredDeviceCount1(role,user_id,key,this.skip,this.limit).subscribe(res=>{
        console.log('ExpiredDeviceList',res);
        this.filtes = res;
        this.abc(this.filtes);
      })

    }

    renewedVehList(key){
      this.filterId = 'rv';
      if(key === 'Today'){
        key='today';
        this.keyIdentifier = key;
      }
      if(key === 'Week'){
        key='week';
        this.keyIdentifier = key;
      }
      if(key === 'Month'){
        key='month';
        this.keyIdentifier = key;
      }
          
      var role = '';
      if(this.superAdmin === true){  role =  'supAdmin' ;}
      if(this.custtype === true){role =  'Dealer' ;}
      var user_id = this.useridd; 
      this.contactService.getRenewDeviceCount1(role,user_id,key,this.skip,this.limit).subscribe(res=>{
        console.log('renewedDeviceList',res);
        this.filtes = res;
        this.abc(this.filtes);
      })
    }

    latLongDetail(){
      var that =this;
      if (navigator.geolocation) {    
        // if(location.protocol != 'https:'){  
          // this.contactService.getlatLong().subscribe(res=>{
          //   console.log(res);
          // })
        // }else{
          navigator.geolocation.getCurrentPosition(function(position) {
            console.log('Position=>',position);
            let geocoder = new google.maps.Geocoder();
           var d_lat= position.coords.latitude;
           var d_lng=position.coords.longitude;

      let t_latlng = new google.maps.LatLng(d_lat, d_lng);

      let request = {
        latLng: t_latlng
      };
   
      geocoder.geocode(request, function (data, status) {
        var userState;
        if (status == google.maps.GeocoderStatus.OK) {
          if (data[0] != null) {
            var address_show = data[0];
            console.log('var=>' ,address_show);
            for (var ac = 0; ac < data[0].address_components.length; ac++) {
              var component = data[0].address_components[ac];
              switch(component.types[0]) {     
                  case 'administrative_area_level_1':
                      userState  = component.long_name;
                      console.log(userState);
                      break;      
              }
          };
          that.getFuelprice(userState);
          that.currState = userState;
         
          } else {
            userState = 'Maharastra';
            that.currState = userState;
          that.getFuelprice(userState);
          
         
          }
        }
        else {
          userState = 'Maharastra';
          that.currState = userState;
          that.getFuelprice(userState);
          
        }
      })          
        });
        // } 
            }


         

    }

    getFuelprice(ustate){
      console.log(ustate);
      this.contactService.getFuelDetail(ustate).subscribe(fuelprice=>{
        console.log('fuelpricefuelpricefuelprice=>',fuelprice);
        this.fuelCount=[{
          fuel : 'Diesel',
          price:  fuelprice[0]?fuelprice[0].diesel:'--',
          unit : 'litre'
      },{
        fuel : 'Petrol',
        price: fuelprice[0]?fuelprice[0].petrol:'--' ,
        unit : 'litre'
      }]

      })


    }

    langSymbol:boolean=true;
    valueSymbol ='';
    fuelShow:boolean=true;
    getLanguage(){
   
    var that = this;
    var Var = { uid: this.useridd };
     this.contactService.getLanguages(Var).subscribe((res:any)=>{
      console.log('resresresresresresresresresresresresresresresres ',res);
      if(res.timezone != undefined){
        if(res.timezone === 'Asia/Kolkata'){
          this.fuelShow = true;
         }else{
          this.fuelShow = false;
         }
      }
     
   
      var ls = res.currency_code ; 
      if(ls !=undefined){
        if(ls === 'INR'){
          this.langSymbol=true;
        }else{
           this.langSymbol=false;
          this.valueSymbol=res.currency_code;
        }

      }
   
      },err=>{
       console.log(err);
     })
    
    }
 
    totalOdo(dev){
      console.log(dev);
      var from = new Date().setHours(0,0,0);
      var fd = new Date(from).toISOString();
      var to = new Date();
      var td= new Date(to).toISOString();
      var imei = dev._id; 
      var user = dev.user;
      if(typeof user === 'object'){
        var user_id  = user._id;
      }else{
        var user_id = user;
      }
      var suburl = "/summary/distance?from=" + fd +'&to=' + td + '&user=' + user_id + '&device=' + imei;
      this.contactService.get(suburl).subscribe((resp:any) => {  
        console.log('const ka data =>',resp)
        if(resp){
          if(resp.length!=0){
            dev.roadShow=false;
            var dist =  (resp[0].distance).toFixed(2);

            // if(this.distanceVariation[0]=="+"){
            //     var milege=(a/100)*(Number(this.distanceVariation.substring(1)))
            //     console.log("MILEGE->",milege,'-',a);
            //     a=a+milege

            //   }else{
            //     var milege=(a/100)*(Number(this.distanceVariation.substring(1)))
            //     console.log("MILEGE->",milege,'-',a);
            //     a=a-milege
            //   }

            // if(resp[0].device.distanceVariation){
            //   if(resp[0].device.distanceVariation[0]=="+"){
            //     dist=Number(dist)+(Number(dist)/100)*(Number(resp[0].device.distanceVariation.substring(1)))
            //   }else{
            //     dist=dist-(Number(dist)/100)*(Number(resp[0].device.distanceVariation.substring(1)))
            //   }

            // }
            dev.currentODO = dist
          }else{
            dev.roadShow=false;
            dev.currentODO = '0.0';
          }
        }
       },
        err=>{
            dev.roadShow=false;
            dev.currentODO = '0.0';
      })

    }
    reload(){
       window.localStorage['GetDevData'] = 'True'
    // console.log("p1");
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      // console.log('p3');
      this.aa = params['_status'];

      if (this.aa != "OK") {
        window.localStorage['checker'] = 'Data'
      }
      else {
        window.localStorage['checker'] = params['_status'];
      }

    });

   this.latLongDetail()

    }

    

    Indianstate = [ "Andhra Pradesh",
                "Arunachal Pradesh",
                "Assam",
                "Bihar",
                "Chhattisgarh",
                "Goa",
                "Gujarat",
                "Haryana",
                "Himachal Pradesh",
                "Jammu and Kashmir",
                "Jharkhand",
                "Karnataka",
                "Kerala",
                "Madhya Pradesh",
                "Maharashtra",
                "Manipur",
                "Meghalaya",
                "Mizoram",
                "Nagaland",
                "Odisha",
                "Punjab",
                "Rajasthan",
                "Sikkim",
                "Tamil Nadu",
                "Telangana",
                "Tripura",
                "Uttarakhand",
                "Uttar Pradesh",
                "West Bengal",
                "Andaman and Nicobar Islands",
                "Chandigarh",
                "Dadra and Nagar Haveli",
                "Daman and Diu",
                "Delhi",
                "Lakshadweep",
                "Puducherry"]

}
