import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, MenuController } 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;

  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) {
    this.loadMap()
  }

  ionViewDidEnter() {

    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) {
    console.log('gtd')
    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 = {
      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 (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());
      } 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
          // var realTime = (1530183600000 - 1530182700000) / 1000 //in seconds
          // console.log('google time', calcTime);
          // console.log('time taken',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();
  }

}
