import { Component, ViewChild, ElementRef , NgZone} from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { DoctorService } from '../../services/doctor.service';
import { GoogleMapsAPIWrapper, AgmMap, LatLngBounds, LatLngBoundsLiteral, MapsAPILoader} from '@agm/core';

declare var google: any;

@Component({
  selector: 'page-ver-recorrido',
  templateUrl: 'ver-recorrido.html',
})
export class VerRecorridoPage {
@ViewChild('AgmMap') agmMap: AgmMap;
public clickableIcons: boolean = false;
public styles = [{"featureType":"all","elementType":"labels.text.fill","stylers":[{"color":"#7c93a3"},{"lightness":"-10"}]},{"featureType":"administrative.country","elementType":"geometry","stylers":[{"visibility":"on"}]},{"featureType":"administrative.country","elementType":"geometry.stroke","stylers":[{"color":"#a0a4a5"}]},{"featureType":"administrative.province","elementType":"geometry.stroke","stylers":[{"color":"#62838e"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#dde3e3"}]},{"featureType":"landscape.man_made","elementType":"geometry.stroke","stylers":[{"color":"#3f4a51"},{"weight":"0.30"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"poi.attraction","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"poi.business","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi.government","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"poi.place_of_worship","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi.school","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi.sports_complex","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":"-100"},{"visibility":"on"}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"visibility":"on"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#bbcacf"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"lightness":"0"},{"color":"#bbcacf"},{"weight":"0.50"}]},{"featureType":"road.highway","elementType":"labels","stylers":[{"visibility":"on"}]},{"featureType":"road.highway","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.stroke","stylers":[{"color":"#a9b4b8"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"invert_lightness":true},{"saturation":"-7"},{"lightness":"3"},{"gamma":"1.80"},{"weight":"0.01"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#a3c7df"}]}];
lat:any;
lng:any
zoom:number = 16;
origin:any;
origen:any;
destino:any;
destination:any;
started: boolean = false;
terminado: boolean = false;
sus: any = null;
primero: boolean = false;

public renderOptions:any = {
    suppressMarkers: true,
    preserveViewport: true,
    travelMode: 'DRIVING',
    drivingOptions: {
        trafficModel: 'bestguess'
    }
};

public markerOptions:any = {
    origin: {
        icon: 'assets/img/markerTruck.png'
    },
    destination: {
        icon: 'assets/img/goal.png'
    },
};
public driverInformation: any = {
    distance: '',
    actual: '',
    timer: '',
    when: ''
};
public bounds: any;
public norefresh: boolean = false;
  constructor(public navCtrl: NavController,
    private geolocation: Geolocation,
    private ngZone:NgZone,
    private doctorService: DoctorService,
    public mapsAPILoader:MapsAPILoader,
    public navParams: NavParams) {
      this.zoom = 14;
      this.origen = this.navParams.get('origen');
      this.destino = this.navParams.get('destino');
      this.myLocation('constructor');
      this.refresh();

      console.log('destino',this.navParams.get('destino'));
      console.log('origen',this.navParams.get('origen'));

  }
  onMapReady(map: AgmMap) {
    let bounds: LatLngBounds = new google.maps.LatLngBounds();
    bounds.extend(new google.maps.LatLng(this.origen.lat, this.origen.lng));
    bounds.extend(new google.maps.LatLng(this.destino.lat, this.destino.lng));
    map.fitBounds = bounds;
  }
  refresh() {

    this.sus = this.doctorService.serviceQuery(this.navParams.get('id')).subscribe((resp:any)=> {
        let data = resp.data;
        if (data.status == '10') {
            this.started = true;
        }
        else if (data.status == '15') {
            this.terminado = true;
            this.started = true;
        }
        else {
            this.started = false;
            this.terminado = false;
        }

        console.log('update status started: '+this.started);
        console.log('update status terminado: '+this.terminado);
        this.driverInformation = {
            distance: data.tracking_distance,
            actual: data.tracking_actual,
            timer: data.tracking_timer,
            when: data.tracking_when
        };
        if (data.tracking_lat!='0') {
            console.log('update position in map');
            this.ngZone.run(()=>{
                this.lat = parseFloat(data.tracking_lat);
                this.lng = parseFloat(data.tracking_lng);
                this.origin = {
                    lat: this.lat,
                    lng: this.lng
                }
            });

            if (this.primero == false) {
                
            }
            this.primero = true;
            this.myLocation('refresh');
        }
        setTimeout(()=>{           
            if (!this.norefresh) {
                this.refresh(); 
            }
        },5000);
      });

  }
  ionViewDidLeave() {
      if(typeof this.sus == "object") {
        this.norefresh=true;
        this.sus.unsubscribe();
      }
      
  }
  changeDirection(event: any){
    /*

    */
  }
  
  myLocation(from?:string){
      console.log('call my location', from);
      if (this.started == true) {
        //this.ngZone.run(() => {
        this.zoom = 16;
        this.lat = this.origin.lat;
        this.lng = this.origin.lng;
        //this.origin=this.origen;
        this.destination=this.destino;
        //});
      
      }
      else {
          this.zoom = 16;
          this.lat = this.destino.lat;
          this.lng = this.destino.lng;
      }

  }
  

  backButton(){
    this.navCtrl.pop();
  }
}
