import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../contact.service';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { distinctUntilChanged } from 'rxjs/operators';


declare var google: any;


@Component({
  selector: 'app-trip-details',
  templateUrl: './trip-details.component.html',
  styleUrls: ['./trip-details.component.scss']
})
export class TripDetailsComponent implements OnInit {

  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog) { }

  fs : any;
  ls : any;
  emailid : any;
  or : any;
  useridd :any;
  time :any;
  date1:any = new Date();
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust:boolean=false;
  Load : Boolean = false;
  date : any;
  devicesss:any;
  finall:any;
  mb:any;
  logoutbut:boolean;
dealer:boolean;
logo:any;
text:any;
deviceId:any;
userId : any;
d_detail:any;

from_date = new Date();
to_date = new Date();
superAdmin:Boolean = false;
  ngOnInit() {

    this.from_date =new Date( window.localStorage.getItem("from_date"));
    // console.log(this.from_date);

    this.to_date =new Date( window.localStorage.getItem("to_date"));
    // console.log(this.to_date);

    this.deviceId = window.localStorage.getItem("Device_id");
    this.userId =  window.localStorage.getItem("userId");


    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;
  // this.getdev();
    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.trip_details();

  }

  cond:Boolean = false;
    point : any = 0;

  a(){
   
    // console.log(this.point);
    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 ++;
  }
  
    
  }

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

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

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

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

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

}

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

}

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

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

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


}


route_map(){
  this.cond =false;
  this.router.navigateByUrl("routeMapping");

}

  soon(){

  }

  devi(){

  }

  openNav(){

  }


  geo(){

  }

  report(){

  }

  report_speed(){

  }

  ideal(){

  }

  ign(){

  }

  before:any;

  myaccount(){

  }

  mydealer(){

  }
  logout(){

  }

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

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

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


 trip_detail_log =[];
 start_add:any="";
  trip_details(){
    let user = this.userId;
    let devID = this.deviceId;
    // console.log(this.from_date);
    let fDate = this.from_date.toISOString();
    let tdate = this.to_date.toISOString();
    // console.log(fDate);
    // console.log(tdate);

    this.contactService.trip_logs(user,fDate,tdate,devID)
      .subscribe((res)=>{
        this.d_detail = res;
        // console.log(res);
        // console.log(this.d_detail);

        for(let i=0;i<this.d_detail.length;i++){
       
          let lat = this.d_detail[i].start_lat;
          let long = this.d_detail[i].start_long;
          var geocoder = new google.maps.Geocoder();
          var latlng = new google.maps.LatLng(lat,long);
    
          var request = {
            latLng:latlng
          };
    
          geocoder.geocode(request, function(data,status){
            if(status == google.maps.GeocoderStatus.OK){
              if(data[0]!=null){
              
                 this.start_add = data[0].formatted_address;
                //  console.log("address is: " + this.start_add);

               
               
              }else{
                // console.log("No address available")
              }
            }
            else{
              // $scope.allDevices[index].address = device.last_location.lat + ' ,' + device.last_location.long
              // console.log("lat long numeric address  : NA" );
              this.start_add ='NA';
            //  this.trip_detail_log.push({"start_address":this.start_add});
            }
            
          })
          let show_add = this.start_add;
          let fd = this.d_detail[i].start_time.toLocaleString();
          let td = this.d_detail[i].end_time.toLocaleString();
          // console.log(fd);
          // console.log(td);     
          let dist =  this.d_detail[i].distance/1000
          this.trip_detail_log.push({"distance":dist,
          "startTime":fd,
          "endTime":td,
         });
        
          
        }
       

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

  }

}
