import { Component, OnInit,Inject } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
//import { GaugeSegment, GaugeLabel } from 'ng-gauge';
import {ContactService} from '../contact.service';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Data } from '../data';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import {DialogContentExampleDialogComponent} from '../dialog-content-example-dialog/dialog-content-example-dialog.component'
declare var $: any, DataTable: any;
import * as moment from 'moment';
import { DailyDetailsComponent } from './daily-details/daily-details.component';
declare var google: any;
declare var $:any;


@Component({
  selector: 'app-device-report',
  templateUrl: './device-report.component.html',
  styleUrls: ['./device-report.component.scss'],
  providers: [ContactService]
})

export class DeviceReportComponent implements OnInit {
  deviceArr: any=[];
  showSelectdevice:boolean=false;
  identifier = 'daily_report';
  reportArr: any[];
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog) {
   }

  
 
ingData:any
from1:any;
to1:any;
from2:any;
to2:any;
too:any;
date1 : any;
Fromdate:any;
todate:any;
options=[];
option:any;
dataSelect:any=[];


   fs :any;
   ls :any;
   emailid:any;
   or:any;
   useridd:any;
   device_data:any;
   time:any;
   Load:Boolean = false;
   final : any;
   custtype:any;
   cust:boolean=false;
   devicess:any;
   finall:any;
   logo:any;
   text:any;
   ideal(){
    this.router.navigateByUrl("device-report/ideal-report");
  }
  from:any;
  to:any;
  before:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  superAdmin:Boolean = false;

   ngOnInit() {
    this.dataSelect = [];
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;

    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.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    // this.getDevices();
    // this.dailyReport();
    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.testTable();

  //  
  }

 

 

  tab:any;
  exportExcels()
	{
   


	 var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable').clone();
    table[0].querySelector("thead").remove();
    console.log(table[0].querySelector("thead"));
    
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

	    for(j = 0 ; j < this.tab.rows.length ; j++) 
	    {     
	        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
	        //tab_text=tab_text+"</tr>";
	    }

	    tab_text=tab_text+"</table>";
	    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
	    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
	    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

	    var ua = window.navigator.userAgent;
	    var msie = ua.indexOf("MSIE "); 

	    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

	    return (sa);
	}

//   dailyReport() {
//     this.to = this.date1;
//     var x = new Date(this.to).setHours(23,59,59);
//     console.log(x);
//     var to_date = new Date(x).toISOString();
    
//     var d = new Date(this.date1);
//     let a = d.setHours(0, 0, 0, 0)
//     this.from = new Date(a).toISOString();
//     console.log(to_date);
//     console.log(this.from);
//     window.localStorage['from_date'] = this.from;
//     window.localStorage['to_date'] = to_date;
//     var deviceID;

//     if((this.dataSelect.length!=0)&&(this.dataSelect[0].did!='all')){
//        deviceID = this.dataSelect[0].did;
//     }
//     this.Load = true;
//     this.contactService.getDeviceReport(this.useridd,to_date, this.from,deviceID,this.skip,this.limit).subscribe(
//       data => {
//         this.Load = false;
//         this.device_data = data
//         this.finall = this.device_data.data;
    
//         if(this.finall.length==0){       
        
//           this.lastcall=true;
//         }
//         // console.log('dailyReport=>',this.finall);
//       },(err)=>{
//         // console.log("error");
//         this.Load = false;
//         this.firstcall=true;
//       });
//   }

//   // search filter
//   devicesss:any;
//   getDevices(){
//     // let a = {
//     //   value: "All Devices",
//     //   did : "all",
//     //   id : "all"
//     // }
    
//     //     this.options.push(a);
//     this.contactService.getDevice(this.emailid,this.useridd).subscribe(

//       data => {
//         this.devicesss = data

//         for(let i=0;i<this.devicesss.devices.length;i++){

//           if(this.devicesss.devices[i].type_of_device =="Tracker"){

//             let a ={
//               value : this.devicesss.devices[i].Device_Name,      
//               did:this.devicesss.devices[i].Device_ID,
//               id:this.devicesss.devices[i]._id,

//             }
//             this.options.push(a);
//           }

//         }
//           // console.log("deviceObj",this.options);
//           let that = this;
//           setTimeout(()=>{
//             that.loadropdown();
//           },100)  
//       });
//   }


// filterStates(val) {

//   // console.log(val)
//   // console.log(this.options)

//   if (val) {
//     const filterValue:any = val
//      this.dataSelect = this.options.filter( function(d){
  
//       return d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;    
//     });
//     return this.dataSelect;
//   }

// }

skip: number = 0;
limit: number = 10;
firstcall: boolean = false;
lastcall: boolean = true;

// next(){
//   this.lastcall = false;
//   this.skip += 1;
//   this.dailyReport();
// }

// pre(){
//   // console.log(this.skip)
//     if (this.skip > 0) {
//       this.skip -= 1;
//       this.lastcall = false;
//       this.dailyReport();
//     } else {
//       this.lastcall = true;
//       this.firstcall = false;
//     }

// }
tabelObj: any;
callfunction(): void {
  this.Load = true;
  this.deviceArr =  $('#select').multipleSelect('getSelects','value');
  this.tabelObj.draw();
}
dtOptions:any={}
testTable() {
  const that = this;

  this.Load = true;
  $(document).ready(function() {
      that.tabelObj = $('#deviceTable').DataTable({
        dom: 'lBftip',
        buttons: [
          'copy',
          'print',
          'excel'
        ],       
          "processing": true,
          "searching": false,
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: true,
          "scrollY":'60vh', 
          "scrollX": true, 
          "scrollCollapse": true, 
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          "rowCallback": function(row: Node, data: any | Object, index: number){

            $('#edit', row).bind('click', () => {   
              var internalThat  = that;         
              let dialogRef = that.dialog.open(DailyDetailsComponent, {
                // width: '950px',
                // height: '1160px',   
                data: { data:data,date:that.date1}
                
              });
          
              // dialogRef.afterClosed().subscribe(result => {
              //   console.log("result",result);
              //   that.ngOnInit();
             
              //     if(result=="done"){
              //       console.log("resultdone",result)
              //       that.tost1("update");
              //       window.localStorage['DataUpdate'] = 'True';
              //       that.sidebar.sidebarData();       
              //     }
              // });              
            }); 
            },
          ajax: (dataTablesParameters: any, callback) => {
                  that.Load = true;
              dataTablesParameters.op = {};
              dataTablesParameters.select = [];
              dataTablesParameters.find = {};
              var currDay = new Date().getDay();
              var currMonth = new Date().getMonth();
              var currYear = new Date().getFullYear();
              var selectedDay = new Date(that.date1).getDay();
              var selectedMonth  = new Date(that.date1).getMonth();
              var selectedYear = new Date(that.date1).getFullYear();
       
              if((currDay== selectedDay)&&(currMonth==selectedMonth) && (currYear == selectedYear)){
                 var devname = "Device_Name";
                 var devid = "Device_ID";
                 var today_odo = "today_odo";
                 var today_running = "today_running";
                 var today_stopped = "today_stopped";
                 var today_trips = "today_trips"; 
                 var maxSpeed = "maxSpeed";
                 var Mileage = "Mileage";
                 var start_location_lat = "today_start_location.lat";
                 var start_location_long = "today_start_location.long";
                 var end_location_lat = "last_location.lat";
                 var end_location_long = "last_location.long";
              
              }else{
              
                var devid = "imei";
                var devname = "ID.Device_Name";
                var today_odo = "today_odo";
                var today_running = "today_running";
                var today_stopped = "today_stopped";
                var today_trips = "today_trips"; 
                var maxSpeed = "ID.maxSpeed";
                var Mileage = "Mileage";
                var start_location_lat = "start_location.lat";
                var start_location_long = "start_location.long";
                var end_location_lat = "end_location.lat";
                var end_location_long = "end_location.long";

              }

              dataTablesParameters.columns = [
                // {data: "_id" },
                {data: devname},
                {data: devid},
                {data : today_odo},
                {data : today_running},
                {data : Mileage},           
                {data: today_stopped},
                {data :today_trips},
                {data :maxSpeed},
                {data :"t_idling"},
                {data: "t_noGps"},
                {data : "t_ofr" },
                {data : start_location_lat},
                {data : start_location_long},
                {data : end_location_lat},
                {data : end_location_long},
                {data: null, defaultContent: ''}
              ]        


          
              
                var deviceID;
                dataTablesParameters.find.user_id = that.useridd;

                if(that.deviceArr.length != 0){
                
                  var dev_in = {'$in': that.deviceArr};
                     dataTablesParameters.find.devId = dev_in;
                }
        
              // if ((that.dataSelect.length!=0)&&(that.dataSelect[0].did!='all')) {
              //     dataTablesParameters.find.devId = that.dataSelect[0].did;
              // }

              if (that.date1) {
                  var fdate = new Date(that.date1).toISOString()  
                  // dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
                  dataTablesParameters.find.date = fdate        
              };

              var suburl = "";
              suburl += "/devices/daily_report"; 
              if(that.date1 && that.deviceArr.length != 0) {             
              that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
                that.reportArr = [];
                that.reportArr = resp['data'];
                if(that.reportArr.length != 0){
                  var j = 0 ;
                  var finalArr = [];
                  for(var i = 0 ;i<that.reportArr.length;i++){
                   
                  that.clocation_1(that.reportArr[i],function(err,succ){
                    if(err){
                      console.log(err);
                        j++ ; 
                    }else{
                      finalArr.push(succ);
                      console.log(finalArr);
                        j++ ; 
                        if(j  === that.reportArr.length){
                          callback({data : finalArr});
                        }
                    }
                  })

                     that.Load= false;                 
                  }
                }else{
                   that.Load= false;       
                  callback({data : []});

                }
                
                  // that.Load= false;         
                  // callback(resp);
              }, err => {   
                that.Load= false;    
                  
              });
            }else{
                that.Load= false;       
                  callback({data : []});
            }
          },  
          "columns": [
              {
                  "data": "Device_Name",
                  "defaultContent": "",
                  "render": function(data, type, row) {
            
                     if(row.Device_Name){
                      return row.Device_Name
                     }
                     if(row.ID != null){
                      return row.ID.Device_Name;
                     }else{
                       return "";
                     }
                      
                  }
              },
              {
                  "data": "Device_ID",
                  "defaultContent": "",
                  render: function(data, type, row) {
                      return row.Device_ID ? row.Device_ID : row.imei;
                      // if(row.Device_ID){
                      //   return row.Device_ID;
                      //  }else{
                      //   row.imei;
                      //  }
                
                  }
              },
              {
                  "data": "today_odo",
                  render: function(data, type, row) {
                      return data.toFixed(2);
                  }
              }, 
              {
                "data": "Mileage",
                "defaultContent": "_id",
                render: function(data, type, row) {                            
                  var mileage = ((data == undefined)||(data == NaN))?"NA":(row.today_odo/parseFloat(data)).toFixed(2);
                    return mileage;
                }
            },         
              {
                "data": "today_running",
                render: function(data, type, row) {
                  var ign_on:any;
               
                  if(data != undefined){
                   ign_on =  that.millisecondConversion(parseInt(data));
                  }else{
                    ign_on = '0:0'
                  }
              
            

                    return ign_on;
                }
            },         
            { 
              "data": "today_stopped",
              render: function(data, type, row) {

               
                if((data!=undefined)&&(data!=null)&&(data!=NaN)){
                  var stopped = that.millisecondConversion(data); 
                }else{
                  var stopped = "0:0"; 
                }
                return stopped;
              }
          },  
          {
            "data" : "t_idling",
            render : function(data,type,row){
             
              if((data!=undefined)&&(data!=null)&&(data!=NaN)){
                var idleTime = that.millisecondConversion(data); 
              }else{
                var idleTime = "0:0"; 
              }     
              return idleTime ; 
            }
          },  
          {
            "data" : "t_ofr",
            render : function(data,type,row){
            
              if((data!=undefined)&&(data!=null)&&(data!=NaN)){
                var ofr = that.millisecondConversion(data); 
              }else{
                var ofr = "0:0"; 
              }       
                return ofr ;          
            }

          },  
          {
            "data" : "t_noGps",
            render : function(data,type,row){
            
              if((data!=undefined)&&(data!=null)&&(data!=NaN)){
                if((data < 60000)&&(data == undefined)){
                  var seconds = Math.floor((data / 1000) % 60);
                  seconds = (seconds < 10) ? 0 + seconds : seconds;
               
                  var n_gps = "0:0:" + seconds;
                }else{
                  var n_gps_1 = that.millisecondConversion(data);
                  var n_gps = n_gps_1 + ':0' 
                }
              }else{
                var n_gps = "0:0:0"; 
              }       
                return n_gps ;          
            }

          },     
          {
            "data": "today_trips",
            render: function(data, type, row) {
                return data;
            }
        },   
        {
          "data": "maxSpeed",
          "defaultContent": "_id",
          render: function(data, type, row) {
              // return data;
              if(row.maxSpeed){
                return row.maxSpeed
               }
               if(row. ID!= null){
                return row.ID.maxSpeed;
               }else{
                 return 0;
               }
          }
      },
      {
        "data": "startAddress",
        "defaultContent": "",
        render: function(data, type, row) {
       
      
          return data?data : ""; 

        }
    },
    {
      "data": "endAddress",
      "defaultContent": "",
      render: function(data, type, row) {
        
          return data?data : "";
      }
  } ,
   {
          "data":null,
          "defaultContent": "",
          "render":function(data,type,row){   
            return '<button class="btn btn=info btn-sm"><i id="edit" title="Edit Vehicle" style="font-size:20px;color: green" class="fas fa-info-circle"></i></button>'    
      }
    }                
          ], 
             "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4,5,6,7,8,9,10,11,12 ] },
            {
              "targets": '_all',
              "createdCell": function (td, cellData, rowData, row, col) {
                  $(td).css('padding', '18px')
              }
          } 
          // { "width": "40px", "targets": [11,12] }  
           
         
          ]   
      });

  });

}


millisecondConversion(duration){
 
    // var  minutes = Math.floor((duration / (1000 * 60)) % 60);
    // var  hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

    // hours = (hours < 10) ? 0 + hours : hours;
    // minutes = (minutes < 10) ? 0 + minutes : minutes;
  
    // return hours + ":" + minutes ;

var x = duration;
var d = moment.duration(x, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
return  hours + ":" + mins;
  
}


loadropdown() {
  let that = this;
  var script = document.createElement("script");
  script.setAttribute("type", "text/javascript");
  script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
  document.getElementsByTagName("head")[0].appendChild(script);
  
  setTimeout(() => {
    that.showSelectdevice = true;
    $('#select').multipleSelect({
      width: 200,
      placeholder: 'Select device.....',
      filter: true,
    })
   // $('#select').show();
 
  }, 100);
}


getReport(event){
  if(event == 'getExcel'){
    this.exportExcel();
  }else{
    var deviceId: any;
    var tpdata = event ; 
    var that = this;
    var fd = new Date(tpdata.fromDate);
    var td  = new Date(tpdata.toDate);


    
    var x = new Date(tpdata.toDate).setHours(23,59,59);

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

    
    if(event.deviceArr.length==0){
      deviceId=[];
    }else{
      deviceId= event.deviceArr;
    }
    this.deviceArr = deviceId; 
    
    
 
    // this.tabelObj.clear();
    // var aa = [];
    // this.tabelObj.rows.add(aa); 
      this.tabelObj.ajax.reload();    
  }
 
}

clocation_1(latlngObj,cb){

  var outerThis = this;
  var la = '';

  let latLng = {
    lat :"0",
    long:"0"
  };
  if(latlngObj.start_location){
     latLng = {
      lat: latlngObj.start_location.lat?latlngObj.start_location.lat:0,
      long:latlngObj.start_location.long?latlngObj.start_location.long:0
    }
  }
  if(latlngObj.today_start_location){  
     latLng = {
      lat: latlngObj.today_start_location.lat?latlngObj.today_start_location.lat:0,
      long: latlngObj.today_start_location.long?latlngObj.today_start_location.long:0
    }        
  }  

  // if () {
  //   latLng = {
  //     lat: 0,
  //     long: 0
  //   }
  // }
  
  outerThis.contactService.getAddressByApi(latLng).subscribe(res=>{       
    console.log('resaddresscomingfromAPi',res);   
    if(res.message == "Address not found in databse"){
        latlngObj['startAddress'] = "NA"; 
      // cb(null,latlngObj);
        var latLng_1 = {
          lat :"0",
          long:"0"
        };
        if(latlngObj.last_location){
          latLng_1 = {
            lat: latlngObj.last_location.lat?latlngObj.last_location.lat:0,
            long:latlngObj.last_location.long?latlngObj.last_location.long:0
          }
         
        }
        if(latlngObj.end_location){  
          latLng_1 = {
            lat: latlngObj.end_location.lat?latlngObj.end_location.lat:0,
            long: latlngObj.end_location.long?latlngObj.end_location.long:0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res=>{
          console.log('resaddresscomingfromAPi',res);
          if(res.message == "Address not found in databse"){
            latlngObj['endAddress'] = "NA"; 
            cb(null,latlngObj);

        
          }else{
            latlngObj['endAddress'] = res.address; 
            cb(null,latlngObj);
          }

        })
  
    }else{  
      latlngObj['startAddress'] = res.address; 
      var latLng_1 = {
        lat :"0",
        long:"0"
      };
      if(latlngObj.last_location){
        latLng_1 = {
          lat: latlngObj.last_location.lat?latlngObj.last_location.lat:0,
          long:latlngObj.last_location.long?latlngObj.last_location.long:0
        }
       
      }
      if(latlngObj.end_location){  
        latLng_1 = {
          lat: latlngObj.end_location.lat?latlngObj.end_location.lat:0,
          long: latlngObj.end_location.long?latlngObj.end_location.long:0
        }
      }

     
      outerThis.contactService.getAddressByApi(latLng_1).subscribe(res=>{
        console.log('resaddresscomingfromAPi',res);
        if(res.message == "Address not found in databse"){
          latlngObj['endAddress'] = "NA"; 
          cb(null,latlngObj);

      
        }else{
          latlngObj['endAddress'] = res.address; 
          cb(null,latlngObj);
        }

      })

      // cb(null,latlngObj);
    }
  })

}

// --------------------New Method for excel export-------------------
exportExcel() {
  for(var i=0;i<this.reportArr.length;i++){
    if(this.reportArr[i].Mileage== undefined || (this.reportArr[i].Mileage == NaN))
    {
      this.reportArr[i].Mileage="NA"
    }else{
      this.reportArr[i].Mileage=(this.reportArr[i].today_odo/parseFloat(this.reportArr[i].Mileage)).toFixed(2);
    }
    if(this.reportArr[i].today_running){
      this.reportArr[i].today_running=this.millisecondConversion(parseInt(this.reportArr[i].today_running))
    }else
     this.reportArr[i].today_running='0:0'
    if((this.reportArr[i].today_stopped!=undefined)&&(this.reportArr[i].today_stopped!=null)&&(this.reportArr[i].today_stopped!=NaN)){
      this.reportArr[i].today_stopped=this.millisecondConversion(this.reportArr[i].today_stopped)
    }else
    this.reportArr[i].today_stopped="0:0"

    if((this.reportArr[i].t_idling!=undefined)&&(this.reportArr[i].t_idling!=null)&&(this.reportArr[i].t_idling!=NaN)){
      this.reportArr[i].t_idling=this.millisecondConversion(this.reportArr[i].t_idling)
    }else{
       this.reportArr[i].t_idling="0:0"
    }

     if((this.reportArr[i].t_ofr!=undefined)&&(this.reportArr[i].t_ofr!=null)&&(this.reportArr[i].t_ofr!=NaN)){
      this.reportArr[i].t_ofr=this.millisecondConversion(this.reportArr[i].t_ofr)
    }else{
       this.reportArr[i].t_ofr="0:0"
    }

     if((this.reportArr[i].t_noGps!=undefined)&&(this.reportArr[i].t_noGps!=null)&&(this.reportArr[i].t_noGps!=NaN)){
      if((this.reportArr[i].t_noGps < 60000)&&(this.reportArr[i].t_noGps == undefined)){
                  var seconds = Math.floor((this.reportArr[i].t_noGps / 1000) % 60);
                  seconds = (seconds < 10) ? 0 + seconds : seconds;
                  var n_gps = "0:0:" + seconds;
                  this.reportArr[i].t_noGps=n_gps
                }else{
                  var n_gps_1 = this.millisecondConversion(this.reportArr[i].t_noGps);
                  var n_gps = n_gps_1 + ':0' 
                   this.reportArr[i].t_noGps=n_gps
                }
    }else{
       this.reportArr[i].t_noGps="0:0"
    }
    //  if(this.reportArr[i].maxSpeed){
    //   this.reportArr[i].maxSpeed=this.reportArr[i].maxSpeed
    // }
    // if(this.reportArr[i].ID!= null){
    //   this.reportArr[i].maxSpeed=this.reportArr[i].ID.maxSpeed
    // }else{
    //    this.reportArr[i].maxSpeed=0
    // }


  }
    this.downloadFile(this.reportArr);
  }

  downloadFile(data, filename = 'Trip Details') {
   
    let arrHeader = ["Device_Name", "Device_ID", "today_odo", "Mileage","today_running","today_stopped","t_idling","t_ofr","t_noGps","today_trips","maxSpeed","startAddress","endAddress"];
    let csvData = this.ConvertToCSV(data, arrHeader);
    let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
    let dwldLink = document.createElement("a");
    let url = URL.createObjectURL(blob);
    let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
    if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
      dwldLink.setAttribute("target", "_blank");
    }
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", "Daily Report.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
  }
  ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    // console.log(array,"<===");Distance	126.94
// Running	2:1
// Idle	1:56
// Stop
    
    let str = 'Daily Report \r\n'+new Date(this.date1).getDate()+"/"+new Date(this.date1).getMonth()+1+"/"+
    new Date(this.date1).getFullYear()+" \r\n \r\n";
    let row = 'S.No,';

    let newHeaders =["Vehicle Name", "Device IMEI", "Total Distance (Km)", "Fuel consumption (Litre)","Ignition ON Time (Hr:Min)","Ignition OFF Time (Hr:Min)","Idle Time (Hr:Min)","Out of reach (Hr:Min)","No GPS (Hr:Min:Sec)","Trips","Max Speed","Start Location","End Location"];

    for (let index in newHeaders) {
      row += newHeaders[index] + ',';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) {
      let line = (i + 1) + '';
      if(i<array.length){}
      for (let index in headerList) {
        let head = headerList[index];       
        line += ',' + this.strRep(array[i][head]);
      }
      str += line + '\r\n';
      
    }
    return str;
  }

  strRep(data) {
    if(typeof data == "string") {
      let newData = data.replace(/,/g, " ");
       return newData;
    }
    else if(typeof data == "undefined") {
      return "-";
    }
    else if(typeof data == "number") {
      return  data.toString();
    }
    else {
      return data;
    }
  }




}



 // let geocoder = new google.maps.Geocoder();
      // let t_latlng = new google.maps.LatLng(latlngObj.lat, latlngObj.long);

      // let request = {
      //   latLng: t_latlng
      // };
      // geocoder.geocode(request, function (data, status) {
      //   if (status == google.maps.GeocoderStatus.OK) {
      //     if (data[0] != null) {
        
      //       var addressObj = {
      //         "lat":latlngObj.lat,
      //         "long":latlngObj.long,
      //         "address":la
      //       }
      //         this.contactService.saveAdd(addressObj).subscribe(res=>{
                  
      //          cb(null,data[0].formatted_address);      
      //         },err=>{  
      //           console.log("couldn't save address");           
      //          cb(null,data[0].formatted_address);      
      //         })        
      //     } else {
         
      //     cb(null,"No address available");
      //     }
      //   }
      //   else {
      //     cb(null,'NA');
      //   }

      // })