import { Component, ViewChild, ElementRef, NgZone, Input, Renderer2, OnDestroy } from '@angular/core';
import { NavController, Platform, NavParams, ToastController, PopoverController, AlertController, LoadingController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { HttpClient } from '@angular/common/http';
import {} from 'googlemaps';
import { MapsAPILoader, GoogleMapsAPIWrapper, AgmMap } from '@agm/core'

import * as moment from 'moment';
import { AdsMedia } from '../../pages/popovers/ads/ads';
import { DoctorService } from '../../services/doctor.service';
import { Pata } from '../../pata';
import { Storage } from '@ionic/storage';
import { IonPullUpFooterState } from 'ionic-pullup';

import { TrackingProvider } from '../../providers/tracking/tracking';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { isRightSide } from 'ionic-angular/umd/util/util';

// import { EMPTY_MAP } from '@angular/core/src/view';



// declare var google: any;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage implements OnDestroy {

 
  public lat: number = -33.4727092;
  public lng: number = -70.7699146;
  public state: boolean = true;
  public list: any = [];
  public buscando: any = [];
  public buscar: string = '';
  public distanceRequirement: string = '';
  public timeRequirement: string = '';
  public map: any;
  public searching: boolean = false;
  public active: any = { profile_id: '0' };
  public secureSearch: string = '';
  public activo: any = null;
  public verDetalle: boolean = false;
  public vistaDeals: string = 'map';
  public arrayService: any = [];
  public polyline: any = [];
  public waitings: any = [];
  public LatestDate: any;
  public loading: any;
  public secuencia: any;
  public shownGroup = null;
  public checkStart: string = "NoIniciado";
  public idServIniciado: any = 0;  
  public voy: string = '';
  public renderOptions:any = {
    suppressMarkers: true,
    preserveViewport: true,
    travelMode: 'DRIVING',
    drivingOptions: {
      trafficModel: 'best_guess'
    }
  };

  public markerOptions:any = {
    origin: {
        icon: 'assets/img/markerTruck4.png'
    },
    destination: {
        icon: 'assets/img/goal.png'
    },
  };

  public footerState: IonPullUpFooterState;
  public inputLocationOrigen: any;
  public inputLocationDestino: any;
  public fromPlacesRetiro: any = false;
  public fromPlacesEntrega: any = false;
  public fromPlacesBusca: any = 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"}]}];

  public shipment: any = false;
  public latitude: number = 0;
  public longitude: number = 0;
  public zoom: number = 14;
  public showPlaceSavedRetira: any = false;
  public showPlaceSavedEntrega: any = false;
  public showPlaceSavedBusca: any = false;
  public entrega: any;
  public mibuscar:any
  public miUbicacion: any;
  public miUbicacionCoords: any;
  public loaderPlaces: any = false;
  public addresses: any = [];
  public origenShow = false;
  public destinoShow = false;
  public myPlaceDialog: any = '';
  public requerimentBtnRetira: any = false;
  public requrimentBtnEntrega: any = false;
  public clickableIcons: boolean = false;
  public driverInformation: any = {
    distance: '',
    actual: '',
    timer: ''
  };
  private iconWait = {
    url: 'assets/img/icono.camion.png', 
    scaledSize: {
      height: 32,
      width: 32
    }
  };
  public sLoad: any = null;

  public requirementOk: any = false;
  public diponibilidadOk:any = false;
  public latRetiro: number;
  public longRetiro: number;
  public latEntrega: number;
  public longEntrega: number;
  public origin: any;
  public destination: any;
  public idorigin: any;
  public iddestination: any;
  public originBusca: any;
  public OrigenCityName:any;
  public DestinoCityName:any;
  public OrigenBuscarCityName:any
  public comentario: string = '';
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private doctorService: DoctorService,
    private geolocation: Geolocation,
    private toastCtrl: ToastController,
    public popoverCtrl: PopoverController,
    public http: HttpClient,
    public loadingCtrl: LoadingController,
    private service: Pata,
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone,
    public alertCtrl: AlertController,
    public platform: Platform,
    public locationTracker: TrackingProvider,
    private storage: Storage,
    public renderer: Renderer2,
    private iab: InAppBrowser
  ) {
    this.shipment = false;
    this.footerState = IonPullUpFooterState.Collapsed;

    this.loading = loadingCtrl.create();

    this.gotome();
    setTimeout(() => {
      this.setCurrentPosition();
    }, 400);
    this.driverServicesInProgress();
    /*
    setInterval(() => {
       console.log(this.origin,this.destination);
    }, 2000);
    */
  }
  waze() {
    let toto = this.destination.lat+','+this.destination.lng;
    window.open('https://www.waze.com/ul?ll='+toto+'&navigate=yes', '_system');
  }
  ionViewDidEnter(){
    this.cleanMap();
  }
  ionViewDidLeave(){
    this.cleanMap();
  }
  ngOnDestroy(): void {
    
  }
  changeDirectionConductor(event: any){
    console.log('this.checkStart', this.checkStart);
    if (this.idServIniciado > 0 && event.routes && event.routes[0]) {
      /*console.log(event.routes[0]);*/
      this.driverInformation = {
        distance: event.routes[0].legs[0].distance.text,
        actual: event.routes[0].summary,
        timer: event.routes[0].legs[0].duration.text
      };
      this.doctorService.serviceUpdateDriverData( this.idServIniciado, 
                                                  this.driverInformation.distance, 
                                                  this.driverInformation.actual, 
                                                  this.driverInformation.timer,
                                                  this.locationTracker.UbicacionLat(),
                                                  this.locationTracker.UbicacionLng()).subscribe((data:any) => {
        //update ok
      });
    }
  }
  changeDirectionReq(event: any){
   console.log(event);
   this.distanceRequirement = event.routes[0].legs[0].distance.text;
   this.timeRequirement =  event.routes[0].legs[0].duration.text;
  }
  toggleFooter() {
    this.footerState = this.footerState == IonPullUpFooterState.Collapsed ? IonPullUpFooterState.Expanded : IonPullUpFooterState.Collapsed;
  }
  toggleGroup(group) {
    if (this.isGroupShown(group)) {
      this.shownGroup = null;
    } else {
      this.shownGroup = group;
    }
  };
  isGroupShown(group) {
    return this.shownGroup === group;
  }
  footerExpanded() {

  }
  footerCollapsed() {

  }
  start(id,latd,lngd,destino,city,notes) {
    
    let alert = this.alertCtrl.create({
      title: 'Confirmar inicio',
      subTitle: 'Notificaremos al usuario que vás en camino y podrá ver tu posición',
      /*inputs: [
        {
          name: 'guia',
          placeholder: 'Ingrese folio'
        }
      ],*/
      buttons: [
        {
          text: 'Cancelar',
          role: 'cancel',
          handler: data => {
            
          }
        },
        {
          text: 'Iniciar',
          handler: data => {
            this.voy = (destino+", "+city).toUpperCase();
            /*
            this.loading = this.loadingCtrl.create();
            this.loading.present();
            this.doctorService.setServiceGuia(id,data.guia).subscribe((data:any)=> {
              this.loading.dismiss();
              if (data.res == "OK") {
                this.origin = { lat: this.locationTracker.UbicacionLat(),lng: this.locationTracker.UbicacionLng() }
                this.destination = { lat: parseFloat(latd), lng: parseFloat(lngd) }
                this.trakingStart(id);
                this.toggleFooter();
              } else {
                this.service.showMsg(data.msg);
              }
            });
            */
           this.comentario = notes;
           this.origin = { lat: this.latitude,lng: this.longitude }
           this.destination = { lat: parseFloat(latd), lng: parseFloat(lngd) }
           this.trakingStart(id);
           this.toggleFooter();
          }
        }
      ]
    });
    alert.present();
  }
  stop(id,estado) {

    let alert = this.alertCtrl.create({
      title: 'Confirmar termino',
      subTitle: 'Notificaremos al usuario que el pedido fue '+estado,
      /*inputs: [
        {
          name: 'guia',
          placeholder: 'Ingrese folio'
        }
      ],*/
      buttons: [
        {
          text: 'Cancelar',
          role: 'cancel',
          handler: data => {
            
          }
        },
        {
          text: 'Confirmar',
          handler: data => {
           this.trakingStop(id,estado);
           this.toggleFooter();
          }
        }
      ]
    });
    alert.present();

    
    
  }
  starintervalo() {
    if (!this.locationTracker.queryInProgress()) {
      this.locationTracker.startTracking();
      this.secuencia = setInterval(() => {
        this.sendTracktoserver();
      }, 5000);
    }
  }
  trakingStart(id) {
    this.loading = this.loadingCtrl.create();
    this.loading.present();
    let params = {
      'service_id': id,
      'lat': this.locationTracker.UbicacionLat(),
      'lng': this.locationTracker.UbicacionLng()
    }

    this.doctorService.setStartService(params).subscribe((data) => {
      this.loading.dismiss();
      if (data["res"] == "ok" || data["res"] == "OK") {
        this.checkStart = "iniciado";
        this.idServIniciado = id;
        this.starintervalo();
      } else {
        this.service.showMsg(data["msg"]);
      }
    }), (err) => {
      this.loading.dismiss();
      this.service.showMsg("Ha ocurrido un error");
    }
  }
  trakingStop(id,estado) {
    let params = {
      'service_id': id,
      'estado': estado,
      'lat': this.locationTracker.UbicacionLat(),
      'lng': this.locationTracker.UbicacionLng()
    }
    this.checkStart = "NoIniciado";
    this.driverServices();

    this.doctorService.setStopService(params).subscribe((data) => {
      if (data["res"] == "ok" || data["res"] == "OK") {
        this.service.showMsg(data["msg"]);
        clearInterval(this.secuencia);
        this.cleanMap();
      } else {
        this.service.showMsg(data["msg"]);
      }
    }), (err) => {
      this.service.showMsg("Ha ocurrido un error");
    }
  }
  cleanMap(){
    this.polyline=[];
    this.setCurrentPosition();
    this.destination = this.origin;  
  }
  sendTracktoserver() {
    let params = {
      'service_id': this.idServIniciado,
      'lat': this.locationTracker.UbicacionLat(),
      'lng': this.locationTracker.UbicacionLng()
    }  
    this.latitude = this.locationTracker.UbicacionLat();
    this.longitude= this.locationTracker.UbicacionLng();

    this.origin = {lat: this.latitude, lng: this.longitude};
    /*this.doctorService.sendPositionTraking(params).subscribe((data) => {
    }), (err) => {
      console.log("Ha ocurrido un error");
    }*/
  }
  
  driverServices() {
    this.loading = this.loadingCtrl.create();
    this.loading.present();
    this.sLoad = this.doctorService.getDriverService().subscribe((data:any) => {
      if (data["res"] == "OK") {
        for (let i = 0; i < data.data.length; i++) {
          data.data[i].dist = this.getDistanceFromLatLonInKm(this.latitude,this.longitude,data.data[i].lat,data.data[i].lng);
        }
        data.data.sort(function(a, b) {
          return parseFloat(a.dist) - parseFloat(b.dist);
        });
        this.arrayService = data.data;
        this.checkStart = "NoIniciado";
        this.loading.dismiss();
      } else {
        this.loading.dismiss();
        this.service.showMsg(data["msg"]);
      }
    }),(err) => {
      this.service.showMsg("Ha ocurrido un error");
      this.loading.dismiss();
    }
  }
  gotome(){
    this.latitude = -33.4727092;
    this.longitude = -70.7699146;
    this.geolocation.getCurrentPosition().then((position) => {
      this.latitude = position.coords.latitude;
      this.longitude = position.coords.longitude;
    });
  }
  
  driverServicesInProgress() {
    this.doctorService.getDriverServiceInProgress().subscribe((data) => {
      if (data["res"] == "OK") {
        var servicoenprogreso = data["data"];
        if (servicoenprogreso.length == 0) {
          this.driverServices();
          this.setCurrentPosition();
        } 
        else {
          var serviData = servicoenprogreso[0];
          this.comentario = serviData.notes;
          var idServicio = serviData["id"];
          this.checkStart = "iniciado";
          this.idServIniciado = idServicio;
          this.voy = (serviData["address_street"]+", "+serviData["address_city"]).toUpperCase();
          this.ngZone.run(() => {
            //this.origin = { lat: parseFloat(serviData.last_lat),lng: parseFloat(serviData.last_lng) }
            this.origin = { lat: this.latitude,lng: this.longitude }
            this.destination = { lat: parseFloat(serviData.lat), lng: parseFloat(serviData.lng) }
            this.starintervalo();
          });
          //this.drawpolylineService(this.idServIniciado);
        }
      } else {
        this.service.showMsg(data["msg"]);

      }
    }),(err) => {
      this.service.showMsg("Ha ocurrido un error");
    }
  }
  /*drawpolylineService(idServicio) {
    this.loading = this.loadingCtrl.create();
    this.loading.present();
    let param = idServicio;
    console.log("servicio para draw:" + idServicio);
    this.doctorService.getTrucking(param).subscribe((data) => {
      console.log("sigue array para draw");
      console.log(data)
      this.loading.dismiss();
      if (data["res"]=="OK"){
        this.ngZone.run(() => {
       this.polyline = data["data"];
       let posicion = (this.polyline.length - 1);
        this.LatestDate = this.polyline[posicion]["in_time"];
        this.latitude = this.polyline[posicion]["lat"];
        this.longitude = this.polyline[posicion]["lng"];
      })
    }else{
        this.service.showMsg(data["msg"]);
        this.setCurrentPosition();
      }
    }),(err) => {
      this.service.showMsg("Ha ocurrido un error");
      this.loading.dismiss();
    }
  }*/
  getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
    var R = 6371; // Radius of the earth in km
    var dLat = this.deg2rad(lat2-lat1);  // deg2rad below
    var dLon = this.deg2rad(lon2-lon1); 
    var a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
      Math.sin(dLon/2) * Math.sin(dLon/2)
      ; 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c; // Distance in km
    return d.toFixed(2);
  }
  deg2rad(deg) {
    return deg * (Math.PI/180)
  }
  close() {
    this.verDetalle = false;
  }
  private reverseGeocode(latitud, longitude) {
    var geocoder = new google.maps.Geocoder;
    let latlng = { lat: latitud, lng: longitude }
    geocoder.geocode({ 'location': latlng }, (result, status) => {
      this.ngZone.run(() => {
        if (status.toString() === 'OK') {
            this.requerimentBtnRetira = true;
            this.miUbicacion = result[0]["formatted_address"].toUpperCase();
            this.fromPlacesRetiro = true;
            this.OrigenCityName = result[0]["formatted_address"].toUpperCase();
            console.log(result[0]["formatted_address"]);
        } else {
          this.miUbicacion = latlng["lat"] + ', ' + latlng["lng"];
        }
      });
    });

  }
  private setCurrentPosition(setVar?: number) {
    let inputField: HTMLElement = <HTMLElement>document.getElementById('txtEntrega');
    inputField && inputField.focus();
    
    this.geolocation.getCurrentPosition().then((position) => {
      if (setVar == 1) {
        this.reverseGeocode(position.coords.latitude, position.coords.longitude);
        this.miUbicacionCoords = { lat: position.coords.latitude, lng: position.coords.longitude }
        this.origin = { lat: position.coords.latitude, lng: position.coords.longitude }
        this.showPlaceSavedRetira = false;
        this.showPlaceSavedEntrega = false;
        //this.showButton();
      }
      this.latitude = position.coords.latitude;
      this.longitude = position.coords.longitude;
      /*this.zoom = 17;*/
    });
  }
  public loadAPIWrapper(map) {
    this.map = map;
  }
  dateformat(fecha) {
    var fecha_mm = moment(fecha);
    return moment(fecha_mm.format(), moment.ISO_8601).format();
  }
}


