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';
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';


@Component({
  selector: 'app-travel-path-report',
  templateUrl: './travel-path-report.component.html',
  styleUrls: ['./travel-path-report.component.scss']
})
export class TravelPathReportComponent implements OnInit {
  pathDuration = [
    {label  :"1 Minutes",interval : "1"},
    {label  :"5 Minutes",interval : "5"},
    {label  :"10 Minutes",interval : "10"},
    // {label  :"45 Minutes",interval : "45"},
    // {label  :"60 Minutes",interval : "60"}
  
  ];
  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;
  private finalise = new Subject<void>();
  constructor(private contactService: ContactService,private router: Router,private _service:ReportService,public snackBar: MdSnackBar) { 
     this._service.invokeEventFortravelPathReportt.pipe(
      takeUntil(this.finalise)
    ).subscribe(value => {
        if(value){
         this.travelPathReport(value); 
       }
      });
  }
   ngOnDestroy(){
    this.finalise.next(void 0);
  }
  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,
    //           // 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(value){
  if(value=="getExcel"){
    this.exportExcel()
  }else{


  this.Fromdate=value.fromDate;
this.todate=value.toDate
// this.dataSelect[0].did=value.deviceArr
  // tpdata.fromDate;
  //   var td  = tpdata.toDate;
  //   if(event.deviceArr.length
  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)) < Number(this.travelPat_duration.interval)){
//   Rlabel = JSON.stringify(this.travelPat_duration.interval)  + " " + "Minutes";
//   Rinterval = JSON.stringify(this.travelPat_duration.interval);
// }

// 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((value.deviceArr.length == 0)||(value.deviceArr[0]==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 });toISOString();
    return;
  }

 

this.pathReport=[];
  var payload ={
    "to":new Date(this.todate).toISOString(),
    "from" : new Date(this.Fromdate).toISOString(),
    "device" : value.deviceArr[0].id[0],
    "interval" : this.travelPat_duration.interval
  }


  this.Load = true;
  console.log( value.deviceArr[0]);
  
  var device_name = value.deviceArr[0].name ; 
  console.log("payload=>",payload);

  this.contactService.getTravel_path_report(payload).subscribe(res=>{
    clearTimeout(this.clear_interval);
    this.Load = false;
    this.disable_pdf_button = true;
 
    for(let i = 0; i <res.length ; i++){
      if(res[i]!=null){
        res[i].data.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 });
  })
  }

}

getcummulative_distance(gps_report,index){
 
  if(index == 0){
    return 0.00;
  }else{
    var cum_distance = parseFloat(gps_report[index].data.odo)-parseFloat(gps_report[0].data.odo);
    // console.log("hjdfhhdfh",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].data.odo)-parseFloat(gps_report[index_1-1].data.odo);
    // console.log(cum_distance);
    return Math.abs(parseFloat(cum_distance.toFixed(2)));  
  }

}

export_pdf(){
  console.log('pdf');
  // jsPDF(orientation, unit, format

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



}

// changeDate(path){
//   console.log("inside function");
 
//   this.todate = new Date(this.Fromdate.setMinutes(this.Fromdate.getMinutes() + parseInt(path.interval)))
//   console.log("this.travelPat_duration",this.todate);

// }


filterStates(val) {

  // console.log(val)
  // 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;    
    });
    
      return this.dataSelect;

  }
}
locationOnDemand : boolean =true;
shownote:boolean = false;
// selectedStatus(ev){
//   // if(ev.checked === true){
//   //   this.locationOnDemand = !this.locationOnDemand;
//   //   this.disable_pdf_button = true;
//   //   this.shownote = true;
//   //   this.noteForpdf = "Please wait while we are fetching Address, We recommend you not to download pdf before complete address conversion !!!"
//   //   this.convertAddress();

//   // }else{
//     // clearTimeout(this.clear_interval);
//     // this.shownote = false;
//     this.noteForpdf = ""
//     this.disable_pdf_button = false;
//     // this.travelPathReport()
//     // this.locationOnDemand = !this.locationOnDemand

//   // }
// }

locationAddress: any;
// getAddress(gps_report) {
//   var outerThis = this;
//   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;
//   }


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

//   var request = {
//     latLng: latlng
//   };

//   var that = this;
//   geocoder.geocode(request, function (data, status) {
//     if (status == google.maps.GeocoderStatus.OK) {
//       if (data[0] != null) {
//         outerThis.address_show = data[0].formatted_address;
//           gps_report.locationAddress = outerThis.address_show;
//       } else { 
//         gps_report.locationAddress = "No address available";     
//       }
//     }
//     else {
//       outerThis.address_show = outerThis.lattitude + ", " + outerThis.longitude;
//       gps_report.locationAddress = outerThis.address_show;
//     }

//   })
// }

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

}
onChange(value){

  console.log("ACTUAL",this.travelPat_duration.interval,'-',value)
}

getAddress(data,i){
   const that = this;
   let geocoder = new google.maps.Geocoder();
   
               let t_latlng
               var d_lat;
               var d_lng;
               console.log(data);
               
              //  if(typeof(data.startAddress)=='object'){
                  t_latlng = new google.maps.LatLng(data.geoJSON.coordinates[1],data.geoJSON.coordinates[0]);
                  d_lat=data.geoJSON.coordinates[1];
                  d_lng=data.geoJSON.coordinates[0]
              //  }else{
              //     t_latlng = new google.maps.LatLng(data.endLat, data.endLng);
              //     d_lat=data.endLat;
              //     d_lng=data.endLng
              //  }

                let request = {
                  latLng: t_latlng
                };
                geocoder.geocode(request, function (data, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    if (data[0] != null) {
                      var liveAdd = data[0].formatted_address;
                      that.pathReport[i].address=data[0].formatted_address
                      console.log(data[0].formatted_address);
                      that.saveAddress(d_lat, d_lng,liveAdd)
                    } 
                  }
                  else {
                    console.log(data);
                    // that.liveAdd = 'NA';
                    that.pathReport[i].address="Address not found"
                    console.log(that.pathReport[i]);
  
                  }
                }
                )
}

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

  }

}