import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../contact.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { MdSnackBar } from '@angular/material';
declare var google :any;
declare var jsPDF : any;
import * as moment from 'moment';
declare var CanvasJS:any
declare var html2canvas:any
@Component({
  selector: 'app-tempreture-report',
  templateUrl: './tempreture-report.component.html',
  styleUrls: ['./tempreture-report.component.scss']
})
export class TempretureReportComponent implements OnInit {
  pathDuration = [
    {label  :"1 Minutes",interval : "1"},
    {label  :"2 Minutes",interval : "2"},
    {label  :"5 Minutes",interval : "5"},
    {label  :"10 Minutes",interval : "10"},
    // {label  :"60 Minutes",interval : "60"}
  
  ];
  hide:boolean=false
  public lineChartData: Array<any> = [
    { data: [0, 0, 0, 0, 0, 0, 0], label: 'Temperature' },
  ];
  public lineChartLabels: Array<any> = ['', '', '', '', '', '', ''];
  public lineChartOptions: any = {
    responsive: true,
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: false,
          max: 6000,
          min: 0
        }
      }]
    }

  };
  public lineChartColors: Array<any> = [
    { // grey
      backgroundColor: 'rgba(148,159,177,0.2)',
      borderColor: 'rgba(148,159,177,1)',
      pointBackgroundColor: 'rgba(148,159,177,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(148,159,177,0.8)'
    },
    { // dark grey
      backgroundColor: 'rgba(77,83,96,0.2)',
      borderColor: 'rgba(77,83,96,1)',
      pointBackgroundColor: 'rgba(77,83,96,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(77,83,96,1)'
    },
    { // grey
      backgroundColor: 'rgba(148,159,177,0.2)',
      borderColor: 'rgba(148,159,177,1)',
      pointBackgroundColor: 'rgba(148,159,177,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(148,159,177,0.8)'
    }
  ];
  public lineChartLegend: boolean = true;
  public lineChartType: string = 'line';
  deviceNameForPDF: any;
  startTime: any;
  endTime: any;
  startAddress: any;
  endAddress: any;



  // events
  public chartClicked(e: any): void {
    // console.log(e);
  }

  public chartHovered(e: any): void {
    // console.log(e);
  }
  travelPat_duration ={label  :"10 Minutes",interval : "10"};
  superAdmin: any;
  fs: any;

  disable_pdf_button : boolean = false;
  ls: any;
  emailid: any;
  useridd: any;
  custtype: any;
  devicesss: any;
  finall: any;
  options: any=[];
  option : any;
  dataSelect: any=[];
  cust: boolean;
  mb: string;
  logoutbut: boolean;
  dealer: boolean;
  or: any;
  logo: any;
  text: any;
  Fromdate = new Date();
  todate = new Date();
  showError : boolean = false;
  Load: boolean =false;
  pathReport: any;
  address_show: string;
  lattitude: any;
  longitude: any;
  start_add_lat: any;
  start_add_long: any;
  clear_interval: any;
  noteForpdf: string;
  showGraph:boolean=false;
  constructor(private contactService: ContactService,private router: Router,public snackBar: MdSnackBar) { }

  ngOnInit() {

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


    var fTime = new Date().setHours(0,0,0);
    this.Fromdate = new Date(fTime);
    // var to_date = new Date();
    // this.todate.setMinutes(this.todate.getMinutes() + parseInt(this.travelPat_duration.interval));
    // this.Fromdate.setHours()

    

    this.contactService.getDevice(this.emailid,this.useridd).subscribe(
      
      data => {
        this.devicesss = data
     
        this.finall = (this.devicesss.devices);

        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,
              viewValue:this.devicesss.devices[i].Device_Name,
              did:this.devicesss.devices[i].Device_ID,
              id:this.devicesss.devices[i]._id,
              user:this.devicesss.devices[i].user,
              image:this.devicesss.devices[i].supAdmin?this.devicesss.devices[i].supAdmin.imageDoc:''
              // email: this.devicesss.devices[i].Email_ID,
              // deviceType: this.devicesss.devices[i].type_of_device
            }
            this.options.push(a);
          // }

        }
          // console.log(this.options);
     

      });

      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'];  

  

}

travelPathReport(){
  var that = this;
  if((this.Fromdate == undefined)||(this.todate == undefined)){
    let message1="Please Select Date";
    let action:any;
    this.snackBar.open(message1, action, {
      duration: 5000,
      
    }); 
    // this._flashMessagesService.show("Please Select Date", { cssClass: 'alert-danger', timeout: 3000 });

    return;
  }

  if(this.Fromdate.getTime() > this.todate.getTime()){
    let message1="From Date cannot be greater than to date...";
    let action:any;
    this.snackBar.open(message1, action, {
      duration: 5000,
      
    }); 
    // this._flashMessagesService.show("Please Select Date", { cssClass: 'alert-danger', timeout: 3000 });

    return;
  }

  var diff = (this.todate.getTime() - this.Fromdate.getTime()) / 3600000;
  console.log(diff);

var now  = this.todate;
var then = this.Fromdate;

// var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var difference =this.todate.getTime() - this.Fromdate.getTime();
// var d = moment.duration(ms);
// var s = d.format("hh:mm:ss");
var hour = (difference / (60*60*1000));
// var hourCount = Number(hour);
var diff_hr = Math.round(hour);
console.log('diff_hr',diff_hr);
if(diff_hr>(24*15)){
  let message1="Date difference should not be greater then 15 Days";
    let action:any;
    this.snackBar.open(message1, action, {
      duration: 5000, 
    }); 
    return;
}

// let r_I = difference / (1000*60) ; 
// let report_Interval = r_I/360 ;



// let Rlabel;
// let Rinterval ;
// // this.travelPat_duration.interval = JSON.stringify(Math.round(report_Interval)) ; 
//  Rlabel = JSON.stringify(Math.round(report_Interval))  + " " + "Minutes";
//  Rinterval = JSON.stringify(Math.round(report_Interval));
//  if(parseInt(JSON.stringify(report_Interval)) < 10){
//   Rlabel = JSON.stringify(10)  + " " + "Minutes";
//   Rinterval = JSON.stringify(10);
// }

// this.pathDuration.push({label  :Rlabel,interval : Rinterval}) ;
// this.travelPat_duration = {label  :Rlabel,interval : Rinterval};

// // outputs: "48:39:30"
// if (diff > 24) { 
//   let message1="Date difference should not be more than 24 hours...";
//   let action:any;
//   this.snackBar.open(message1, action, {
//     duration: 5000,
//   }); 
//   return;
//  }

  if((this.dataSelect.length == 0)||(this.dataSelect[0].did==undefined)){
    let message1="Please Select Device";
    let action:any;
    this.snackBar.open(message1, action, {
      duration: 5000,
      
    }); 
    // this._flashMessagesService.show("Please Select Device", { cssClass: 'alert-danger', timeout: 3000 });
    return;
  }

 

this.pathReport=[];
  var payload ={
    "to":this.todate,
    "from" : this.Fromdate,
    "device" : this.dataSelect[0].did,
    "interval" : this.travelPat_duration.interval
  }


  this.Load = true;
  var device_name = this.dataSelect[0].viewValue ; 
  console.log("payload=>",payload);

  this.contactService.getTravel_path_report(payload).subscribe(res=>{
    clearTimeout(this.clear_interval);
    // this.Load = false;
    this.disable_pdf_button = true;
    // var reportArr1=res;
    var reportArr1=  res.filter(function (el) {
                  return el != null;
                });
    var finalArra=[]
    const that = this;
     var j = 0;
     if(reportArr1.length>0){
       for (var i = 0; i < reportArr1.length; i++) {
                       that.clocation_1(reportArr1[i], function (err, succ) {
                         if (err) {
                           console.log(err);
                           j++;
                         } else {
                           // console.log(succ);
                           succ['index']=j
                           finalArra.push(succ);
                           // console.log(finalArra,j);
                           j++;
                           if (j === reportArr1.length) {
                             that.Load = false;
                              finalArra.sort(function(a:any,b:any){
    
                             return new Date(b.date).valueOf() - new Date(a.date).valueOf();
                           });
                           console.log(finalArra);
                           that.pathReport=finalArra;
                           that.hide=true;
                           that.getdata(that.pathReport)
                             // callback({ data: that.finalArr });
                           }
                         }
                       })
       
                      
                     }

     }else{
        this.Load = false;
     }

 
    // for(let i = 0; i <res.length ; i++){
    //   if(res[i]!=null){
    //     res[i].Device_name = device_name;
    //     this.pathReport.push(res[i]);
    //   }else{
    //     console.log('resnullresnullresnullresnullres=>',res[i]);
    //   }
    // }

    // if(this.pathReport.length == 0){  
    //   this.disable_pdf_button = false;
    //   let message1="No Data Available";
    //   let action:any;
    //   this.snackBar.open(message1, action, {
    //     duration: 5000,      
    //   }); 
    //   // this._flashMessagesService.show("No Data Available", { cssClass: 'alert-danger', timeout: 3000 });
    // }else{
    //   this.convertAddress();

    // }

  },err=>{
    this.Load = false;
    let message1="Please Try Again";
      let action:any;
      this.snackBar.open(message1, action, {
        duration: 5000,
        
      }); 
    // this._flashMessagesService.show("Please Try Again", { cssClass: 'alert-danger', timeout: 3000 });
  })


}

   clocation_1(latlngObj, cb) {
     if(latlngObj==null){
       cb(null, latlngObj);
     }
    var outerThis = this;
    var la = '';

    let latLng = {
      lat: "0",
      long: "0"
    };
  
      latLng = {
        lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
        long: latlngObj.longDecimal ? latlngObj.longDecimal : 0
      }
    
  
    // if () {
    //   latLng = {
    //     lat: 0,
    //     long: 0
    //   }
    // }

    outerThis.contactService.getAddressByApi(latLng).subscribe(res => {
      if (res.message == "Address not found in databse") {
        var adata = {
          iden : 'noaddress',
          latlng : latLng
        }
        latlngObj['address'] = adata;
        // cb(null,latlngObj);
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
    
          latLng_1 = {
            lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
        long: latlngObj.longDecimal ? latlngObj.longDecimal : 0
          }
        

        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            var bdata = {
              iden : 'noaddress',
              latlng : latLng_1
            }
        
            latlngObj['address'] = bdata;
            latlngObj['device_name']=outerThis.deviceName
            cb(null, latlngObj);


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

        })

      } else {
        latlngObj['address'] = res.address;
        latlngObj['device_name']=outerThis.deviceName
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
    
          latLng_1 = {
            lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
        long: latlngObj.longDecimal ? latlngObj.longDecimal : 0
          }
        
 


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            var cdata = {
              iden : 'noaddress',
              latlng : latLng_1
            }
        
            latlngObj['address'] = cdata;
            latlngObj['device_name']=outerThis.deviceName
            cb(null, latlngObj);


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

        })

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

  }

getcummulative_distance(gps_report,index){
 
  if(index == 0){
    return 0.00;
  }else{
    var cum_distance = parseFloat(gps_report[index].odo)-parseFloat(gps_report[0].odo);
    // console.log(cum_distance);
    return Math.abs(parseFloat(cum_distance.toFixed(2)))  ;
  }
 
}

get_distance(gps_report,index_1){
  if(index_1 == 0){
    return 0.00;
  }else{
    var cum_distance = parseFloat(gps_report[index_1].odo)-parseFloat(gps_report[index_1-1].odo);
    // console.log(cum_distance);
    return Math.abs(parseFloat(cum_distance.toFixed(2)));  
  }

}

export_pdf(){
  console.log('pdf');
  var image=""
  console.log(this.dataSelect);
  
    if(this.dataSelect[0].image.length != 0){
        var str =  this.dataSelect[0].image[0]
        var splitStr = str.split('/');
        var concatStr ='';
       for(var i=1 ; i< splitStr.length ; i++){      
         if(i > 0){ 
          var tt = splitStr[i];   
          concatStr += '/'+tt ; 
         }
       }
       image='https://www.oneqlik.in' + concatStr
       console.log("IMAGE==>",image);
      
      }

  this.startTime=this.pathReport[0].fromTime
  this.endTime=this.pathReport[0].toTime;
   this.startAddress=this.pathReport[0].address
  this.endAddress=this.pathReport[this.pathReport.length-1].address
  var name=this.deviceName+" Temperature Report from "+moment(this.Fromdate).format('lll')+" to "+moment(this.todate).format('lll')+'.pdf'
 
  console.log(name,this.startTime,this.endTime,image);
  
  const that=this
  // var element = $('#graph');
        var pdfOptions = {
            orientation: "landscape", // One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
            unit: "pt",              //Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
            format: "legal"            //One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
        };

        // var doc = new jsPDF(pdfOptions);

        // var pageWidth = doc.internal.pageSize.width-20;
        // var width  =  pageWidth;

        html2canvas(document.getElementById('graph'), { useCORS: true,letterRendering: 1, allowTaint : true, onrendered : function (canvas) {
           
            let img = new Image();
      img.src = canvas.toDataURL('image/png');
      console.log(img.src);
      
      img.onload = function () {
        console.log("IN ");
        let pdf = new jsPDF(pdfOptions);
        var header = function(data) {
                      pdf.setFontSize(15);
                      pdf.setTextColor(40);
                      pdf.setFontStyle('normal');
                     
                      // doc.addImage(dataUrl, 'JPEG', data.settings.margin.left, 20, 30, 30);
                      pdf.text("Temperature Report", data.settings.margin.left, 50);
                    };
         var element = $('#graph');
              var imgWidth = element.width();
                var imgHeight = element.height();
                var pageWidth = pdf.internal.pageSize.width+20;
                var height =  (pageWidth * imgHeight)/ imgWidth
        console.log(img);
        // that.showGraph=false;
        pdf.addImage(img, 'PNG', 5, 102 , pageWidth, 180);

        let finalY = pdf.previousAutoTable.finalY;
            that.toDataURL(image, function (dataUrl) {
                  if(image)
                   pdf.addImage(dataUrl, 'JPEG', 4, 4, 45, 45);
                  let finalY = pdf.previousAutoTable.finalY;
                  pdf.text('Temperature Report', 55, 20);
                   var header = function(data) {
                      pdf.setFontSize(15);
                      pdf.setTextColor(40);
                      pdf.setFontStyle('normal');
                      console.log(dataUrl);
                     
                    };
                    pdf.autoTable({html:"#headerTable",margin:{bottom:140,left:55,right:8,top:30},theme:'plain'});
                 
                  // doc.autoTable({
                  //     head: outerThis.headRows(),
                  //     // margin: { top: 80 },
                  //     startY: doc.autoTable.previous.finalY + 200,
                  //     body: outerThis.bodyRows(outerThis.finalArr.length, outerThis.finalArr),
                  //     // beforePageContent: header,
                  // });
                  // doc.save(name);
             
                  pdf.autoTable({
                  theme: 'grid',
                  html: '#deviceTable', 
                  //  margin: {top: 320},
                   startY: pdf.autoTable.previous.finalY + 200,
              
            });
            pdf.save(name);
              });
};

}
 });

}

 toDataURL(url, callback) {
     console.log(url);
     
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            var reader = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }
    // var imgWidth = element.width();
    //       var imgHeight = element.height();

    //       var height =  (pageWidth * imgHeight)/ imgWidth;

    //       var imgData = canvas.toDataURL('image/png');
    //       console.log(imgData);
          
    //       doc.addImage(canvas.toDataURL('image/png'), 'PNG', 5, 30 , width, height);


        // html2canvas(element, {
        //     useCORS: true, // MUST
        //     onrendered: function(canvas) {
        //         var imgWidth = element.width();
        //         var imgHeight = element.height();

        //         var height =  (pageWidth * imgHeight)/ imgWidth;

        //         var imgData = canvas.toDataURL('image/png');
        //         console.log(imgData);
                
        //         doc.addImage(imgData, 'PNG', 5, 30 , width, height);
        //     }

        //   })

    //       html2canvas(document.querySelector('#graph'), {useCORS: true},function(canvas) {
    //   let img = new Image();
    //   img.src = canvas.toDataURL('image/png');
    //   img.onload = function () {
    //     let pdf = new jsPDF('landscape', 'mm', 'a4');
    //     pdf.addImage(img, 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
    //     pdf.save('certificate.pdf');
    //   };
    // })
    // };


  // this.noteForpdf = '';
  // var f_date = moment(this.Fromdate).format('lll'); 
  // var t_date =moment(this.todate).format('lll');
  // var date_combine = f_date + '-' + t_date;
  // let doc = new jsPDF('l','pt','a4');
  // doc.text('Travel Path Report', 350, 30);
  // doc.text(date_combine, 250, 60);
  

  // doc.addHTML(document.getElementById("exportPdf"), function() {
  //   var tpr ="";
  //    doc.save("obrz.pdf");
  // });

  // var specialElementHandlers = {
  //   '#editor': function (element: any, renderer: any) {
  //     return true;
  //   }
  // };

  // doc.autoTable({
  //   theme: 'striped',
  //   html: '#deviceTable', 
  //   margin: {top: 100},
  //   // styles :  {
  //   //   cellWidth : 50
  //   // },     
  //   willDrawCell: data => {
  //     console.log('data=>',data);

  //   //  console.log('data=>',data.row.index.length);
     
  //   // if(data.cell.text[0] === "Device"){
  //   //   data.row.cells[0].styles.fillColor =  [224,224,224];
  //   // }
  //     if((data.row.index === 0)||(data.cell.text[0] === "Device")){ 
  //       // data.row.cells[0].styles.halign = 'center';
  //       data.row.cells[1].styles.halign = 'center';
  //       data.row.cells[2].styles.halign = 'center';
  //       data.row.cells[3].styles.halign = 'center';
  //       data.row.cells[4].styles.halign = 'center';
  //       data.row.cells[5].styles.halign = 'center';
  //       data.row.cells[6].styles.halign = 'center';
  //       // data.row.cells[0].styles.fillColor =  [224,224,224];
  //       // doc.setLineHeightFactor()
  //     }  
  //     // data.row.cells[0].styles.halign = 'center';
  //     data.row.cells[1].styles.halign = 'center';
  //     data.row.cells[2].styles.halign = 'center';
  //     data.row.cells[3].styles.halign = 'center';
  //     data.row.cells[4].styles.halign = 'center';
  //     data.row.cells[5].styles.halign = 'center';
  //     data.row.cells[6].styles.halign = 'center';


    
  //   }
    
  // });
  // var pdfNameStr = travel_path_report
  // doc.save('travel_path_report.pdf');



// }
deviceName
filterStates(val) {
  this.deviceName=val
  console.log(this.deviceName);

  // console.log(this.options)

  if (val==""){

    this.dataSelect = [];
    // console.log("deviceValue",this.dataSelect);
  } else{
  
    const filterValue:any = val;
    
     this.dataSelect = this.options.filter(function(d){
      var t = d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase());
    //  this.option = this.options[i];
  
   
      return t > -1;    
    });
    console.log(this.dataSelect);
    
      return this.dataSelect;

  }
}
locationOnDemand : boolean =true;
shownote:boolean = false;
locationAddress: any;

addressLink = "";
getlink(gps_report){
  console.log("gps_report");
  if ((gps_report.latDecimal== undefined)||(gps_report.latDecimal == null)) {
    this.lattitude = null;
  } else {
      this.lattitude =gps_report.latDecimal;  
  }
  if((gps_report.longDecimal == undefined)||(gps_report.longDecimal == null)){
    this.longitude = null;
  }else{
    this.longitude =gps_report.longDecimal;
  }
  this.addressLink =  'https://maps.google.com/?q=' + this.lattitude + ',' + this.longitude;
  return this.addressLink ; 
}

closeProcess:any;
convertAddress(){
  
  // console.log('gRport=>',gRport);
 
  var i = 0;
  this.closeProcess= this.pathReport.length;
  var outerThis =this;
  console.log('this.closeProcess',this.closeProcess);
  // let conditionalLogic = 2000 ; 
  function f() {
    let start_add_lat:any;
    let start_add_long:any;
    if((outerThis.pathReport[i].latDecimal!=null)&&(outerThis.pathReport[i].longDecimal!=null)){
      start_add_lat =  outerThis.pathReport[i].latDecimal;
      start_add_long= outerThis.pathReport[i].longDecimal; 
    }else{
      start_add_lat = null;
      start_add_long= null;  
    }

    var geocoder = new google.maps.Geocoder();
    var latlng_start = new google.maps.LatLng(start_add_lat,start_add_long);
   
    var request={
      latLng:latlng_start
    }

    let apiPayload = {
      lat : start_add_lat,
      long  : start_add_long

    }

    outerThis.contactService.getAddressByApi(apiPayload).subscribe(res=>{
      // console.log('addressresponse=>', res);
      if (res.message == "Address not found in databse") {
        // conditionalLogic = 5000 ; 
     
        geocoder.geocode(request, function (data, status) {
          let start_add: any;
          if (status == google.maps.GeocoderStatus.OK) {
            if (data[0] != null) {
              start_add = data[0].formatted_address;
              if (start_add == "Antarctica") {
                start_add = "NA";
              }

            } else {
              start_add = "NA";
            }
            outerThis.pathReport[i-1].address = start_add;
          }
          else {
            start_add = "NA";    
           
          }
          outerThis.pathReport[i-1].address = start_add;


        })
        }else{   
            // conditionalLogic = 100 ;         
            outerThis.pathReport[i-1].address = res.address;       
        } 
    },err=>{

    })

  
    i++;
    if( i < outerThis.closeProcess ){
     
      outerThis.clear_interval =  setTimeout( f,2000 );
    }
  }
  f();

}



tab:any;

exportExcel() {

  var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
  var textRange; var j=0;
  this.tab = 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
  // tab_text= tab_text.replace(/<th>Edit</th>/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);
}

gettempExac(temp){
  if(temp){
    return (parseFloat(temp)/10).toFixed(2)
  }else{
    return 0;
  }

}

  viewGraph(ev){
    console.log(ev);
    
    this.showGraph=ev.checked

    

  }

   getdata(final) {
    //  this.showGraph=true;
    final.sort((x, y) => +new Date(y.date) - +new Date(x.date));
    let fi = [];
    let f2=[]
    let time = [];
    this.lineChartLabels.length = 0;
    for (let q = final.length - 1; q > 0; q--) {
      fi.push(final[q].temp?(parseFloat(final[q].temp)/10).toFixed(2) :0);
       f2.push(final[q].temp2?(parseFloat(final[q].temp2)/10).toFixed(2) :0);
      let t = new Date(final[q].date).toLocaleTimeString();
      // console.log(t);
      //let k = JSON.stringify(final[q].time).split("T")[1].split(".")[0];
      this.lineChartLabels.push(t)
    }
    this.Load = false;
    this.lineChartData = [{
      label: "Temp1",
      data: fi
    },
    {
      label: "Temp2",
      data: f2
    }
  ];

  }

  
}
