import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams,MenuController } 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";
import { TranslateService } from "@ngx-translate/core";
import { Storage } from "@ionic/storage";

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;
  lastPos: any;
  count: number = 0
  markers: any;
  tempLast: any;
  userMarkers: any;
  lang: string = 'en';

  constructor(public navCtrl: NavController, public navParams: NavParams, private data: dataService, private geolocation: Geolocation, private myservice: Myservice, private translate: TranslateService, private storage:Storage, private menu :MenuController) {
  }

  ionViewDidEnter() {
    this.menu.swipeEnable(false)
    this.storage.get('lang').then(lang => {
      if (lang != null) {
        this.translate.use(lang)
        this.lang = lang;
      }
      else {
        this.translate.use('en')
      }
    })

    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((This.driver.driverId)).on("value", function (snapshot) {

        if (This.count > 1)
          This.lastPos = res_arr

        var res_arr = []
        res_arr = (<any>Object).entries(snapshot.val()).map(e => Object.assign(e[1], { key: e[0] }));

        if (This.count == 0)
          This.lastPos = res_arr//inially last and current position is same

        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 });//hide default marker

          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 = {
            path: "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z", //svg image for car
            fillColor: '#000',
            fillOpacity: .6,
            anchor: new google.maps.Point(10, 25),
            strokeWeight: 0,
            scale: 1,
            rotation: 0
          };

          if (This.markers) {
            This.markers.setMap(null);
          }

          if (This.userMarkers)
            This.userMarkers.setMap(null);

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

          var markerUser = new google.maps.Marker({//user marker
            position: pickLoc,
            map: This.map
          });

          This.markers = marker
          This.userMarkers = markerUser

          var cur = driverLoc
          var lastPosn = new google.maps.LatLng(This.lastPos[0].lat, This.lastPos[0].lng)
          var heading = google.maps.geometry.spherical.computeHeading(lastPosn, cur)
          dimage.rotation = heading;
          marker.setIcon(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());
        This.count++
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

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

    This.locSubs = this.geolocation.watchPosition()
      .filter((p) => p.coords !== undefined) //Filter Out Errors
      .subscribe(position => {

        if (this.count > 0) {
          This.lastPos[0].lat = this.tempLast[0]
          This.lastPos[0].lng = this.tempLast[1]
        }

        this.tempLast = [position.coords.latitude, position.coords.longitude]

        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 = {
          path: "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z", //svg image for car
          fillColor: '#000',
          fillOpacity: .6,
          anchor: new google.maps.Point(10, 25),
          strokeWeight: 0,
          scale: 1,
          rotation: 0
        };

        if (This.markers) {
          This.markers.setMap(null);
        }

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

        new google.maps.Marker({//destination marker
          position: destLoc,
          map: This.map
        });

        This.markers = marker

        var cur = new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
        var lastPosn = new google.maps.LatLng(This.lastPos[0].lat, This.lastPos[0].lng)
        var heading = google.maps.geometry.spherical.computeHeading(lastPosn, cur)
        dimage.rotation = heading;
        marker.setIcon(dimage);

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

          locRef.orderByChild("id").equalTo((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();
    this.menu.swipeEnable(true)
  }
}
