import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { dataService } from "../../providers/common.service";
import * as firebase from 'firebase';
import { Geolocation } from '@ionic-native/geolocation';
import { Myservice } from "../../providers/myservice";

declare var google;
@IonicPage()
@Component({
  selector: 'page-map',
  templateUrl: 'map.html',
})
export class MapPage {
  @ViewChild('map') mapElement: ElementRef;
  map: any;
  directionsDisplay: any;
  bookData: any;
  temp: boolean = false;
  locSubs: any;
  driver: any;
  pushed: number = 0;

  constructor(public navCtrl: NavController, public navParams: NavParams, private data: dataService, private geolocation: Geolocation, private myservice: Myservice) {
  }

  ionViewDidEnter() {
    this.geolocation.getCurrentPosition().then((resp) => {
      this.loadMap(resp.coords.latitude, resp.coords.longitude);
      this.driver = this.data.getdriverData();
      this.bookData = this.data.getbookingData();
      console.log(this.bookData)
      var This = this;

      var locRef = firebase.database().ref().child('/drivers/');

      locRef.orderByChild("id").equalTo(Number(This.driver.driverId)).on("value", function (snapshot) {
        var res_arr = []
        res_arr = (<any>Object).entries(snapshot.val()).map(e => Object.assign(e[1], { key: e[0] }));
        console.log(res_arr[0])

        if (res_arr[0].started == true) {
          // This.directionsDisplay.setMap(null);
          This.loadMap(resp.coords.latitude, resp.coords.longitude);
          locRef.off("value");
          This.startRide();
        }
        else {
          var directionsService = new google.maps.DirectionsService;

          This.directionsDisplay.setMap(This.map);
          This.directionsDisplay.setOptions({ suppressMarkers: true });

          var pickLoc = new google.maps.LatLng(This.bookData.pickLat, This.bookData.pickLng);
          var driverLoc = new google.maps.LatLng(res_arr[0].lat, res_arr[0].lng);

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


          This.calculateAndDisplayRoute(directionsService, This.directionsDisplay, pickLoc, driverLoc);
        }
      });
    }).catch((error) => {
      console.log('Error getting location', error);
    });
  }

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

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

  startRide() {
    this.temp = true
    console.log('started')
    var This = this;

    This.locSubs = this.geolocation.watchPosition()
      .filter((p) => p.coords !== undefined) //Filter Out Errors
      .subscribe(position => {
        console.log(position.coords.longitude + ' ' + position.coords.latitude);

        var directionsService = new google.maps.DirectionsService;

        This.directionsDisplay.setMap(This.map);
        This.directionsDisplay.setOptions({ suppressMarkers: true });

        var destLoc = new google.maps.LatLng(This.bookData.dropLat, This.bookData.dropLng);
        var myLoc = 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: myLoc,
          map: This.map,
          icon: dimage
        });
        console.log(marker)

        // if (google.maps.geometry.spherical.computeDistanceBetween(myLoc, destLoc) < 50){
        var locRef = firebase.database().ref().child('/drivers/');

        locRef.orderByChild("id").equalTo(Number(This.driver.driverId)).on("value", function (snapshot) {
          var res_arr = []
          res_arr = (<any>Object).entries(snapshot.val()).map(e => Object.assign(e[1], { key: e[0] }));
          console.log(res_arr[0])
          if (res_arr[0].started == false) {
            This.pushed++
            console.log(This.pushed)
            This.myservice.show_loader()
            locRef.off();
            if (This.pushed == 1)
              This.navCtrl.setRoot('PaymentPage')
          }
        })
        // }
        This.calculateAndDisplayRoute(directionsService, This.directionsDisplay, myLoc, destLoc);
      });
  }

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

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