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 * as firebase from 'firebase';
import { Validators, FormGroup, FormBuilder } from '@angular/forms'
import { dataService } from "../../providers/common.service";
import { Myservice } from "../../providers/myservice";
import { user } from "../../models/mymodel";

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;
  local:user

  constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public storage: Storage, private geolocation: Geolocation, private firebase: fireService, private db: AngularFireDatabase, private formBuilder: FormBuilder, private data: dataService, private myservice:Myservice) {

    this.locForm = this.formBuilder.group({
      pickLoc: ['', Validators.required],
      dropLoc: ['', Validators.required]
    })
  }

  ionViewDidEnter() {
    this.data.setbookingData('')

    this.storage.get('user_data').then(data=>{
      if(data){
        this.local = data
      }
    })

    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]) {
            // console.log(results)
            This.locForm.controls['pickLoc'].setValue(results[0].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();
    console.log(place)
    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 }
    });

    var search = place.formatted_address

    this.myservice.load_post({ 'keyword': place.name, 'userid': this.local.id, 'location': search},'setSearch').subscribe(response=>{
    })
    
    if (type == 0) {
      this.p_lat = lat
      this.p_lng = lng
      this.markers[1] = marker
      this.locForm.controls['pickLoc'].setValue(place.name)
    }
    else if (type == 1) {
      this.d_lat = lat
      this.d_lng = lng
      this.markers[2] = marker
      this.locForm.controls['dropLoc'].setValue(place.name)
    }

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

  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, 'pickArea': this.locForm.value.pickLoc, 'dropArea': this.locForm.value.dropLoc}
      this.data.setbookingData(data)
      let modal = this.modalCtrl.create('RidepopPage');
      modal.onDidDismiss(data=>{
        if(data){
          let modal1 = this.modalCtrl.create('RidenowPage',{type:data});
          modal1.onDidDismiss(dat=>{
            if(dat){
              this.navCtrl.push('AddcouponPage', { rate: dat });
            }
          })
          modal1.present();
        }
      })
      modal.present();
    }

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

  }
