import { Component, OnInit, Inject } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { GetdevdetailComponent } from '../../const/getdevdetail/getdevdetail.component';
import { ContactService } from '../../contact.service';
declare var google: any;
declare var swal: any;
@Component({
  selector: 'app-create-trip',
  templateUrl: './create-trip.component.html',
  styleUrls: ['./create-trip.component.scss']
})
export class CreateTripComponent implements OnInit {
  addLat: number;
  addlng: number;
  AddMapObj: any;
  addressString: any;
  source_address: any;
  poiRadius:any;
  POINAME:any;
  TripName:any;
  vehData: any;
  destLat: any;
  destLong: any;
  directionsService: any;
  directionsDisplay: any;
  useridd: any;
  IMEI: any;
  Dealer: any;
  supAdmin: any;

  constructor(public dialogRef: MdDialogRef<GetdevdetailComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,public contactService: ContactService) { 
      console.log("dataVehicle=>",data);
      this.vehData = data;
    }

  ngOnInit() {
    this.mapFunction();
    this.source_address = new google.maps.places.Autocomplete(document.getElementById('txtSource'));

    this.contactService.getdevById(this.vehData.vehicleId).subscribe(res=>{
      var tempObj = JSON.parse(res['_body']);
      console.log("tempObj", tempObj);

      this.IMEI = tempObj._id;
      this.useridd = tempObj.user;
      if(tempObj.Dealer){
        this.Dealer = tempObj.Dealer;

      }
      if(tempObj.supAdmin){
        this.supAdmin  = tempObj.supAdmin;
      }
      console.log("this.IMEI",this.IMEI);
    },err=>{
      console.log(err);
    })

    
  }

  mapFunction(){
    var that = this;
    console.log("add");
  
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {   
        var curr_position :any;
     
        if(that.vehData.LatLng){
           curr_position = {
            lat: that.vehData.LatLng.lat,
            lng: that.vehData.LatLng.long
          } 
          
          that.addLat =  that.vehData.LatLng.lat;
          that.addlng = that.vehData.LatLng.long;
        }else{
           curr_position = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          }  

          that.addLat =  position.coords.latitude;
          that.addlng = position.coords.longitude;
        }
       
        // console.log(this.curr_position);
        that.addLat =  position.coords.latitude;
        that.addlng = position.coords.longitude;
        var mapAdd = new google.maps.Map(document.getElementById('poiAddMap'),{
          center: {lat:  curr_position.lat, lng: curr_position.lng},
          zoom: 15
        });
        // that.AddMapObj = mapAdd;

        var icon1 = {
          url: "./assets/image/ico_direccion.png", // url
          scaledSize: new google.maps.Size(50, 50), // scaled size
        
      };

        var marker = new google.maps.Marker({
          position: curr_position,
          map: mapAdd,
          // draggable:true,
          icon: icon1
        });
    
      
        // google.maps.event.addListener(marker, 'dragend', function() 
        // {
        //     console.log("Inside dragend");
        
        //      var la = marker.getPosition().lat();
        //      var ln = marker.getPosition().lng(); 
        //      that.addLat =la;
        //      that.addlng = ln;

        //      console.log(that.addLat,that.addlng);
         
        // });

                var input = document.getElementById('txtSource');
               
                var searchBox = new google.maps.places.SearchBox(input);
            
                var directionsService = new google.maps.DirectionsService;
                var directionsDisplay = new google.maps.DirectionsRenderer({
                    // draggable: true,
                    map: mapAdd
                  });

                  directionsDisplay.setOptions( { suppressMarkers: true } );
               
                  marker.setMap(null);
              
                searchBox.addListener('places_changed', function() {
                  if(that.markerNew){   
                    that.markerNew.setMap(null);
                  }
                  var places = searchBox.getPlaces();
                  if (places.length == 0) {
                    return;
                  }
                  console.log(places);
               
                  var bounds = new google.maps.LatLngBounds();
                  places.forEach(function(place:any) {
                    console.log(place.formatted_address);
                    console.log(place.geometry.location);
                    that.addressString = place.formatted_address;
                    // that.addLat =  place.geometry.location.lat();
                    // that.addlng = place.geometry.location.lng();
                
                    that.destLat = place.geometry.location.lat();
                    that.destLong = place.geometry.location.lng();
                    var destination = new google.maps.LatLng(that.destLat, that.destLong);
                    console.log(that.destLat,that.destLong);
                    if (!place.geometry) {
                      // console.log("Returned place contains no geometry");
                      return;
                    }

                    var icon2 = {
                      url: "./assets/image/ico_dest_direccion.png", // url
                      scaledSize: new google.maps.Size(50, 50), // scaled size
                    
                  };

                  // var marker = new google.maps.Marker({
                  //   position: curr_position,
                  //   map: mapAdd,
                  //   // draggable:true,
                  //   icon: icon1
                  // });


                  var sourcePoint  = new google.maps.LatLng(curr_position.lat, curr_position.lng);


                  var destPosition = {
                    lat: that.destLat,
                    lng: that.destLong
                  }
            
                    // var marker_dest = new google.maps.Marker({
                    //   position: destPosition,
                    //   map: mapAdd,
                    //   // draggable:true,
                    //   icon: icon2
                    // });
                                     google.maps.event.addListener(directionsDisplay, 'click', function(h) {
                        // console.log(h.latLng.lat(),h.latLng.lng());
                      });
                      // that.computeTotalDistance(that.directionsDisplay.getDirections());
                    
                      directionsDisplay.addListener('directions_changed', function() {
                        that.computeTotalDistance(directionsDisplay.getDirections());
                      });  
                    
                      that.displayRoute(sourcePoint, destination, directionsService,directionsDisplay,mapAdd,icon1,icon2)
                    
        
                    // if (place.geometry.viewport) {
                    //   // Only geocodes have viewport.
                      
                    //   bounds.union(place.geometry.viewport);
                    // } else {
                    //   bounds.extend(place.geometry.location);
                    // }
                    // marker.setPosition(place.geometry.location);
                    // marker.setVisible(true);
                  });
                  mapAdd.fitBounds(bounds);
                });
 
      })  
     }
  }

  totalDistance : any;
  computeTotalDistance(result) {
    var total = 0;
    var myroute = result.routes[0];
    for (var i = 0; i < myroute.legs.length; i++) {
      total += myroute.legs[i].distance.value;
    }
    total = total / 1000;
    this.totalDistance = total;
    document.getElementById('total').innerHTML = total + ' km';
  }

  displayRoute(origin, destination, service, display,map,i1,i2) {
    var that= this;
  
    console.log(origin, destination);
      service.route({
        origin: origin,
        destination: destination, 
        travelMode: 'DRIVING',   
        avoidTolls: true
      }, function(response, status) {
        if (status === 'OK') {
          display.setDirections(response);
          console.log('response=>',response);

          var leg = response.routes[ 0 ].legs[ 0 ];
          that.makeMarker( leg.start_location, i1, "title",map );
          that.makeMarker( leg.end_location, i2, 'title',map );
        }else{
         
          alert('Could not display directions due to: ' + status);
        }
      });
      
  }
  markerNew:any;
  makeMarker(position, icon, title,map){
   
 this.markerNew =  new google.maps.Marker({
      position: position,
      map: map,
      icon: icon,
      title: title
     });
 
  }
  create_trip(){
  
   
  if(this.TripName == undefined){
    console.log("TripName is Mendatory");
  }else{
    var payload = {
      "user": this.useridd,
      "device": this.IMEI,
      "start_loc": {
        "lat": this.addLat,
        "long": this.addlng
      },
      "trip_status": 'Started',
      "end_loc": {
        "lat": this.destLat,
        "long": this.destLong
      },
      "trip_name": this.TripName,
      "start_time": new Date().toISOString()
  
  }

  if(this.Dealer != undefined){
    payload['Dealer'] = this.Dealer;
  }
  if(this.supAdmin != undefined){
    payload['supAdmin'] = this.supAdmin;
  }

  this.contactService.createTrip(payload).subscribe(res=>{
            console.log(res);
            var tripInfo = {};
            tripInfo['reponse'] = res;
            tripInfo['msg'] = 'created'
            this.dialogRef.close(JSON.stringify(tripInfo));
  },err=>{

  })

  }
    
  }
}


