import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular';
import { Storage } from "@ionic/storage";
import { Geolocation } from '@ionic-native/geolocation';
import { fireService } from "../../providers/firebase.service";
import { AngularFireDatabase } from 'angularfire2/database';
import { Myservice } from "../../providers/myservice";
import * as firebase from 'firebase';
import { Validators, FormGroup, FormBuilder } from '@angular/forms'
import { dataService } from "../../providers/common.service";

declare var google;
@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;
  p_lat: number;
  p_lng: number;
  d_lat: number;
  d_lng: number;
  pickLoc: string
  markers = []
  driverMarkers = []
  locForm: FormGroup
  geocoder: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public storage: Storage, private geolocation: Geolocation, private firebase: fireService, private db: AngularFireDatabase, private myservice: Myservice, private formBuilder: FormBuilder, private data: dataService) {
    this.locForm = this.formBuilder.group({
      pickLoc: ['', Validators.required],
      dropLoc: ['', Validators.required]
    })
  }

  ionViewDidEnter() {
    this.geolocation.getCurrentPosition().then((resp) => {
      this.geocoder = new google.maps.Geocoder();
      this.loadMap(resp.coords.latitude, resp.coords.longitude);
      var latlng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
      var This = this;
      This.geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            This.locForm.controls['pickLoc'].setValue(results[3].formatted_address)
            This.p_lat = resp.coords.latitude
            This.p_lng = resp.coords.longitude
          }
        }
        else {
          console.log("Geocoder failed due to: " + status);
        }
      });
    }).catch((error) => {
      console.log('Error getting location', error);
    });

    //drivers loc
    var This = this
    firebase.database().ref().child('/drivers/').orderByChild("status").equalTo('online').on("value", function (snapshot) {
      var res_arr = (<any>Object).entries(snapshot.val()).map(e => Object.assign(e[1], { key: e[0] }));

      //placing marker for each driver
      for (let i = 0; i < res_arr.length; i++) {
        let marker = new google.maps.Marker({
          map: This.map,
          icon: 'assets/img/star-on-big.png',
          position: { lat: res_arr[i].lat, lng: res_arr[i].lng }
        });
        This.driverMarkers[i]=marker
      }
    });
  }

  ionViewDidLoad() {

    var p_autocomplete = new google.maps.places.Autocomplete(document.getElementById("pickUp"));
    var This = this;
    p_autocomplete.addListener('place_changed', function () {
      This.fillAddress(p_autocomplete, 0)
    });

    var d_autocomplete = new google.maps.places.Autocomplete(document.getElementById("drop"));
    d_autocomplete.addListener('place_changed', function () {
      This.fillAddress(d_autocomplete, 1)
    });
  }

  fillAddress(autocomplete, type) {
    if (this.markers.length==3) {
      this.markers[0].setMap(null);
    }
    var place = autocomplete.getPlace();
    var lat = place.geometry.location.lat();
    var lng = place.geometry.location.lng();
    
    let marker = new google.maps.Marker({
      map: this.map,
      position: { lat: lat, lng: lng }
    });
    
    if (type == 0) {
      this.p_lat = lat
      this.p_lng = lng
      this.markers[1] = marker
    }
    else if (type == 1) {
      this.d_lat = lat
      this.d_lng = lng
      this.markers[2] = marker
    }

    if (this.p_lat && this.d_lat) {
      var directionsService = new google.maps.DirectionsService;
      var directionsDisplay = new google.maps.DirectionsRenderer;
      directionsDisplay.setMap(this.map);

      var start = new google.maps.LatLng(this.p_lat, this.p_lng);
      var dest = new google.maps.LatLng(this.d_lat, this.d_lng);

      this.calculateAndDisplayRoute(directionsService, directionsDisplay, start, dest);
    }
    else{
      this.loadMap(lat,lng)
      console.log('121212')
    }
  }

  loadMap(lat, lng) {

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

    let mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var marker = new google.maps.Marker({
      position: latLng
    });

    this.markers.push(marker)

    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
    marker.setMap(this.map);
    for (var i = 0; i < this.driverMarkers.length; i++) {
      this.driverMarkers[i].setMap(this.map);
    }
  }

  calculateAndDisplayRoute(directionsService, directionsDisplay, start, dest) {

    for (var i = 0; i < this.markers.length; i++) {
      if (this.markers[i])
      this.markers[i].setMap(null);
    }
    directionsService.route({
      origin: start,
      destination: dest,
      travelMode: 'DRIVING'
    }, function (response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

    ridemore() {
      var data={pickLat:this.p_lat,pickLng:this.p_lng, dropLat:this.d_lat, dropLng:this.d_lng}
      this.data.setbookingData(data)
      let modal = this.modalCtrl.create('RidepopPage');
      modal.present();
    }

    searchride() {
      let modal = this.modalCtrl.create('SearchridePage');
      modal.present();
    }

  }
