import { Component, OnInit, Inject } from '@angular/core';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';

declare var google:any;

@Component({
  selector: 'app-fuel-objectcomponent',
  templateUrl: './fuel-objectcomponent.component.html',
  styleUrls: ['./fuel-objectcomponent.component.scss']
})
export class FuelObjectcomponentComponent implements OnInit {
  populateHistory:any=[];
  fuelobjectdata: any;
  Load : boolean = false;
  fuelObject: any=[];
  longitude: any;
  lattitude: any;

  address_show: any;
  constructor(private contactService: ContactService,private router: Router,public dialogRef: MdDialogRef<FuelObjectcomponentComponent>,
    @Inject(MD_DIALOG_DATA) public data: any) { 
      console.log(data);
      this.fuelobjectdata = data;
    }

  ngOnInit() {
      this.eventCall();
  }

  eventCall(){
    // this.Load = true;
  // "start_time":"2019-08-02T13:22:06.118Z",
  // "end_time":"2019-08-07T06:22:06.118Z",
  // "imei":"352094089196627",
  // "event":"IN"
  this.fuelObject = [];
    console.log(this.fuelobjectdata);

    var fuelPayLoad = {
      "start_time":this.fuelobjectdata.start_time,
      "end_time":this.fuelobjectdata.end_time,
      "imei":this.fuelobjectdata.imei,
    }

    if(this.fuelobjectdata.event == "in"){
      fuelPayLoad['event'] = "IN"
    }

    if(this.fuelobjectdata.event == "out"){
      fuelPayLoad['event'] = "OUT"
    }    

  // http://localhost:3000/gps/getFuelNotifs
    this.Load = true;
  this.contactService.fueleventCall(fuelPayLoad).subscribe(res=>{
    console.log(res);
    this.Load = false;
    if(res.message=="no event found"){
      this.Load = false;
    }else{

      this.fuelObject = res;
      this.Load = false;
    }
  },err=>{
    this.Load = false;
  })
  }

  cancel(){
    this.dialogRef.close();
  }


  locationAddress: any;
  getAddress(flobj) {
  
    var outerThis = this;
    if (flobj == undefined) {
      this.lattitude = null;
      this.longitude = null;
    } else {
        this.lattitude = flobj.lat;
        this.longitude = flobj.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) {
     
      if (status == google.maps.GeocoderStatus.OK) {
        if (data[0] != null) {
          outerThis.address_show = data[0].formatted_address;
        
          flobj.locationAddress = outerThis.address_show;
         

        } else {
       
          flobj.locationAddress = "No address available";
             
        }
      }
      else {

        outerThis.address_show = outerThis.lattitude + ", " + outerThis.longitude;
       
        flobj.locationAddress = outerThis.address_show;
       

      }

    })
  }


}
