import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';

declare var google;

@IonicPage()
@Component({
  selector: 'page-userlocation',
  templateUrl: 'userlocation.html',
})
export class UserlocationPage {
  @ViewChild('map') mapElement: ElementRef;
  map: any;
  directionsDisplay:any;
  geocoder:any;
  details = this.navParams.get('data')
  locSubs:any;
  temp:boolean = false;
  loc = {'from':'','to':''}
  i:number = 0;

  constructor(public navCtrl: NavController, public navParams: NavParams, private geolocation: Geolocation) {
    this.geolocation.getCurrentPosition().then((resp) => {
      this.loadMap(resp.coords.latitude, resp.coords.longitude);
    })
  }

  ionViewDidEnter() {
    var This = this
    var drop = This.details.drop_latlng.split(',')
    This.geocoder = new google.maps.Geocoder();
    This.locSubs = This.geolocation.watchPosition()
      .filter((p) => p.coords !== undefined) //Filter Out Errors
      .subscribe(position => {
      This.i++;
      var directionsService = new google.maps.DirectionsService;
      
      This.directionsDisplay.setMap(This.map);
      This.directionsDisplay.setOptions({ suppressMarkers: true });

      var pickLoc = new google.maps.LatLng(Number(drop[0]), Number(drop[1]));
        var driverLoc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

          var dimage = {
            url: 'assets/img/map_label.png',
            scaledSize: new google.maps.Size(50, 22),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(25, 12)
          };

          var marker = new google.maps.Marker({
            position: driverLoc,
            map: This.map,
            icon: dimage
          });

        if (This.i == 5) {
        // if (google.maps.geometry.spherical.computeDistanceBetween(pickLoc, driverLoc) < 100) {
          This.temp = true
        }

          This.calculateAndDisplayRoute(directionsService, This.directionsDisplay, pickLoc, driverLoc);

    })
  }

  loadMap(lat, lng) {

    let latLng = new google.maps.LatLng(lat, lng);

    let mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

    this.directionsDisplay = new google.maps.DirectionsRenderer({
      map: this.map,
      preserveViewport: true
    });
  }

  back(){
  	this.navCtrl.pop();
  }

  calculateAndDisplayRoute(directionsService, directionsDisplay, start, dest) {
    var This = this
    directionsService.route({
      origin: start,
      destination: dest,
      travelMode: 'DRIVING'
    }, function (response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
        var bounds = response.routes[0].bounds;
        This.map.fitBounds(bounds);
        This.map.setCenter(bounds.getCenter());
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

  ionViewWillLeave() {
    this.locSubs.unsubscribe();
  }

}
