import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, MenuController, Events } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import * as firebase from 'firebase';
import { AngularFireDatabase } from 'angularfire2/database';
import { driver } from "../../models/mymodel";
import { Storage } from "@ionic/storage";
import { Myservice } from "../../providers/myservice";
import { dataService } from "../../providers/common.service";

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.data.getrideData()
  locSubs: any;
  temp: boolean = false;
  loc = { 'from': '', 'to': '' }
  pushId: string;
  local: driver
  started: boolean = false;
  myloc = []
  waypoints = []
  ride: any;
  markers: any;
  lastPos: any;
  count: number = 0;
  tempPos: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, private geolocation: Geolocation, private db: AngularFireDatabase, private storage: Storage, private myservice: Myservice, private menu: MenuController, private data: dataService, public events: Events) {
    this.loadMap()
  }

  ionViewDidEnter() {

    this.events.publish('driver:locOff', '');

    this.menu.swipeEnable(false);

    this.getStorage()

    var pick = this.details.pickup_latlng.split(',')
    var drop = this.details.drop_latlng.split(',')

    this.geocoder = new google.maps.Geocoder();
    var This = this
    This.locSubs = This.geolocation.watchPosition().filter((p) => p.coords !== undefined) //Filter Out Errors
      .subscribe(position => {

        firebase.database().ref("drivers/" + this.pushId + "/").update({ lat: Number(position.coords.latitude), lng: Number(position.coords.longitude) })

        This.myloc[0] = position.coords.latitude
        This.myloc[1] = position.coords.longitude

        if (This.started == false)
          This.gotoDirection(pick, This.myloc)
        else {
          This.gotoDirection(drop, This.myloc)
          This.waypoints.push({ location: new google.maps.LatLng(position.coords.latitude, position.coords.longitude) })
        }
      })
  }

  loadMap() {

    this.geolocation.getCurrentPosition().then((resp) => {
      var lat = resp.coords.latitude
      var lng = resp.coords.longitude

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

  gotoDirection(dest, myloc) {

    if (this.count == 0)
      this.lastPos = myloc //initially last and curnt postn is same
    else if (this.count > 1) {//count == 1 means last postn is same as initial postn so dont want to check
      this.lastPos = this.tempPos
    }

    this.tempPos = [myloc[0], myloc[1]]

    var This = this;
    var directionsService = new google.maps.DirectionsService;

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

    var destLoc = new google.maps.LatLng(Number(dest[0]), Number(dest[1]));
    var driverLoc = new google.maps.LatLng(Number(myloc[0]), Number(myloc[1]));

    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({
      position: driverLoc,
      map: This.map,
      icon: dimage
    });

    This.markers = marker

    var cur = new google.maps.LatLng(myloc[0], myloc[0])
    var lastPosn = new google.maps.LatLng(This.lastPos[0], This.lastPos[0])
    var heading = google.maps.geometry.spherical.computeHeading(lastPosn, cur)
    dimage.rotation = heading;
    marker.setIcon(dimage);

    if (google.maps.geometry.spherical.computeDistanceBetween(destLoc, driverLoc) < 100) {
      This.loc.to = This.details.drop_area
      This.loc.from = This.details.pickup_area
      This.temp = true
    }

    This.calculateAndDisplayRoute(directionsService, This.directionsDisplay, destLoc, driverLoc);
  }

  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());
        This.count++
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

  startRide() {
    this.myservice.load_post({ status: 'Started', id: this.details.id }, 'changeStatus')
    this.details.actualPick = new Date().getTime()

    this.started = true;
    this.temp = false;
    var This = this;

    firebase.database().ref("drivers/" + This.pushId + "/").update({ started: true })

    var drop = This.details.drop_latlng.split(',')

    This.gotoDirection(drop, This.myloc)
  }

  complete() {
    this.myservice.show_loader()
    this.details.actualDrop = new Date().getTime()

    var pick = this.details.pickup_latlng.split(',')
    var drop = this.details.drop_latlng.split(',')

    var origin = new google.maps.LatLng(pick[0], pick[1]);
    var destination = new google.maps.LatLng(drop[0], drop[1]);
    var service = new google.maps.DistanceMatrixService();

    var This = this
    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        avoidHighways: true,
        avoidTolls: true,
      }, function (response, status) {
        if (response.originAddresses[0] != '') {

          var calcTime = response.rows[0].elements[0].duration.value
          var realTime = (This.details.actualDrop - This.details.actualPick) / 1000//in seconds
          This.details.seconds = realTime
          // var realTime = (1530183600000 - 1530182700000) / 1000 //in seconds
          // console.log('google time', calcTime);
          // console.log('time taken',realTime);
          console.log(realTime)
          if (calcTime < realTime) {
            var extraHr = Math.round(((realTime - calcTime) / 3600) * 100) / 100 //in hrs
            // console.log('extra time',extraHr)
            This.details.timeAmount = Math.round(This.details.extrahour * extraHr)
            // console.log('amt', This.details.timeAmount)
          }
          else
            This.details.timeAmount = 0;
        }
      });


    This.data.setrideData(This.details);

    This.data.setwaypointData(This.waypoints)
    firebase.database().ref("drivers/" + This.pushId + "/").update({ started: false })
    This.navCtrl.push('PaymentPage')
  }

  getStorage() {
    this.storage.get('driver_data').then(data => {
      if (data) {
        this.myservice.hide_loader();
        this.local = data
        var This = this
        var query = firebase.database().ref("drivers/").orderByChild("id").equalTo((data.id))
        query.once("child_added", function (snapshot) {
          This.pushId = snapshot.val().push_id
          console.log(This.pushId)
        });
        This.myservice.load_post({ id: data.id, timetype: This.ride.timetype }, 'getRateCard').subscribe(response => {
          if (response.status == 'success') {
            This.ride = response.data
            This.data.setrateData(This.ride)
          }
        })
      }
    })
  }

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

}
