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

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
  directionsDisplay: any;
  locRef: any
  lastPos: any
  temp: number = 0;
  lang: string = 'en';

  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, private translate: TranslateService, private events:Events) {

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

    this.events.subscribe('user:lang', data => {
      setTimeout(() => {
        this.langTrans();
      }, 500);
    })
  }

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

  ionViewDidEnter() {
    this.langTrans();
    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
    This.locRef = firebase.database().ref().child('/drivers/')
    This.locRef.orderByChild("status").equalTo('online').on("value", function (snapshot) {
      // console.log(This.locRef)
      if (This.temp > 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.temp == 0)
        This.lastPos = res_arr//inially last and current position is same

      var image = {
        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
      };

      //placing marker for each driver
      for (let i = 0; i < res_arr.length; i++) {

        if (This.driverMarkers[i]) {
          if (This.driverMarkers[i].lat != This.lastPos[i].lat && This.driverMarkers[i].lng != This.lastPos[i].lng)//clearing last pos marker
            This.driverMarkers[i].setMap(null);
        }

        let marker = new google.maps.Marker({
          map: This.map,
          icon: image,
          position: { lat: res_arr[i].lat, lng: res_arr[i].lng },
          size: new google.maps.Size(20, 32),
        });

        This.driverMarkers[i] = marker

        ////for changing orientation of car
        var cur = new google.maps.LatLng(res_arr[i].lat, res_arr[i].lng)
        var lastPosn = new google.maps.LatLng(This.lastPos[i].lat, This.lastPos[i].lng)
        var heading = google.maps.geometry.spherical.computeHeading(lastPosn, cur)
        image.rotation = heading;
        marker.setIcon(image);
        ////

        if (i == res_arr.length - 1)
          This.temp++;
      }
    });
  }

  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);
      this.markers[0] = 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 }
    });

    var search = place.formatted_address

    if (type == 0) {//pick position
      this.p_lat = lat
      this.p_lng = lng

      this.markers[1] = marker
      this.locForm.controls['pickLoc'].setValue(place.name)
    }
    else if (type == 1) {//drop position
      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;

      this.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, this.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);
    }

    this.directionsDisplay = new google.maps.DirectionsRenderer
  }

  calculateAndDisplayRoute(directionsService, directionsDisplay, start, dest) {
    for (var i = 0; i < this.markers.length; i++) {
      if (this.markers[i]) {
        this.markers[i].setMap(null);
        this.markers[i] = null;
        // console.log(this.markers[i])
      }
    }
    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() {

    this.myservice.load_post({ 'pickKeyword': this.locForm.value.pickLoc, 'dropKeyword': this.locForm.value.dropLoc, 'userid': this.local.id, 'pickLat': this.p_lat, 'pickLng': this.p_lng, 'dropLat': this.d_lat, 'dropLng': this.d_lng }, 'setSearch').subscribe(response => { })

    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.onDidDismiss(data => {
      if (data) {
        this.locForm.controls['pickLoc'].setValue(data.pickloc)
        this.locForm.controls['dropLoc'].setValue(data.droploc)

        var directionsService = new google.maps.DirectionsService;

        this.directionsDisplay.setMap(this.map);

        var start = new google.maps.LatLng(data.picklat, data.picklng);
        var dest = new google.maps.LatLng(data.droplat, data.droplng);

        this.calculateAndDisplayRoute(directionsService, this.directionsDisplay, start, dest);
      }
    })
    modal.present();
  }

  ionViewWillLeave() {
    this.locRef.off("value");
  }

}
