import { Component, OnInit, NgZone } from '@angular/core';
import { NavController, LoadingController } from '@ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { IchambaService } from 'src/app/services/ichamba.service';
import { AlertService } from 'src/app/services/alert.service';
import { GoogleMaps, GoogleMap, GoogleMapsEvent, LatLng, MarkerOptions, Geocoder, GeocoderRequest, GeocoderResult } from '@ionic-native/google-maps';

declare var google: any;

@Component({
  selector: 'app-hero',
  templateUrl: './hero.page.html',
  styleUrls: ['./hero.page.scss'],
})
export class HeroPage implements OnInit {

  private loading;
  categories: any[] = [];
  categories_input: any[] = [];
  categories_rearranged: any[] = [];
  keywords: any[] = [];
  keywords_string: any[] = [];
  aux_categories: any[] = [];
  myPosition: any = {};
  myAddress: string = null;
  myIntnumber: string = null;
  reference: string = null;
  name: string = null;
  selectedReference: number;
  addressAutocomplete: string = '';
  placesSearch: string = '';
  showinput: boolean = false;
  showif = true;

  constructor(
      private navCtrl: NavController,
      private loadingCtrl: LoadingController,
      private authService: AuthService,
      private alertService: AlertService,
      private ichambaService: IchambaService,
      private googleMaps: GoogleMaps,
      private geocoder: Geocoder,
      private ngZone: NgZone,
  ) { }

  ngOnInit() {
    /*this.categories = ["carpintero","jardinero","abogado","administrador","agente inmobiliario","agente de seguros","albañil",
    "arquitecto","asistente personal","becario","cerrajero","chef","chofer","contratista","contador","diseñador de interiores",
    "cantante","diseñador grafico","edecan","electricista","estilista","servicios financieros","fontanero","fotografo","produccion de videos",
    "hostess","lavado de tapicerias","aire acondicionado","almacenista","ayudante","azulejero","cerrajero automotriz","cortinas metalicas",
    "electrico automotriz","entretenimiento","fisioterapeuta","grua","herrero","ingeniero civil","laminado automotriz","limpieza","limpieza del hogar",
    "mantenimiento","mariachi","masajista","marmolero","mecanico","mercadotecnia","mesero","modelo","musico","niñera","pintor","pintura automotriz",
    "plomero","programador","publicista","recepcionista","remodelacion","repartidor","reparacion de celulares","reparacion de electronicos","soldador",
    "tabla roquero","tapicero","tecnico en gas","tuneame la nave","traductor","tutor","vendedor","veterinario","vidrio y aluminio","reparacion de computadoras",
    "mantenimiento de camiones","consultor","capacitacion","maestro","barbero","agencia de colocacion","agencia de viajes","paseador de perros","banquete",
    "almacenaje","impermeabilizacion","redes de internet"];*/
    this.ichambaService.getCategories()
      .subscribe( categories => {
        this.categories = categories;
        this.aux_categories = categories;
      })
  }

  dismissHero() {
    this.navCtrl.navigateRoot('/landing');
  }

  autocomplete(ev: any) {
    if (!this.addressAutocomplete.trim().length) {
      this.placesSearch = null;
    }
    console.log(this.addressAutocomplete)
    new google.maps.places.AutocompleteService().getPredictions({ input: this.addressAutocomplete }, predictions => {
      this.ngZone.run(() => {
        this.placesSearch = predictions;
        console.log(predictions);
      });
    });
  }

  geoloc(place_id: string, place_description: string, place_intnumber: string) {
    this.myAddress = place_description;
    this.myIntnumber = place_intnumber;
    console.log(place_id);
    this.hidelist();
    new google.maps.Geocoder().geocode({ placeId: place_id }, coordinates  => {
      this.ngZone.run(() => {
        console.log(coordinates[0].geometry.location.lat() + ", " + coordinates[0].geometry.location.lng());
        this.myPosition = {
          latitude: coordinates[0].geometry.location.lat(),
          longitude: coordinates[0].geometry.location.lng()
        }
      });
    });
  }

  selected_reference(ev: any) {
    console.log(ev.target.value);
    this.selectedReference = ev.target.value;
    if (this.selectedReference == 5) {
      this.showinput = true;
    } else {
      this.showinput = false;
    }
  }

  addHero(){
    for (var i of this.categories_input) {
      this.categories_rearranged.push(i.value);
    }
    if (this.keywords.length > 0) {
      for (var i of this.keywords) {
        this.keywords_string.push(i.value);
      }
    }

    if (this.name && this.categories_input && this.myAddress && this.myPosition.latitude && this.myPosition.longitude && this.selectedReference){
      if (this.selectedReference == 5 && this.reference) {
        this.loadingCtrl.create().then((overlay) => {
          this.loading = overlay;
          this.loading.present();
        });

        this.ichambaService.addHero(this.name, this.categories_rearranged.join(','), (this.keywords_string.join(', ') == "" ? null : this.keywords_string.join(', ')), this.myAddress, this.myPosition.latitude, this.myPosition.longitude, this.selectedReference, this.reference).subscribe(
          data => {
            this.loading.dismiss();
              this.alertService.presentToast(data['message']);
              this.navCtrl.navigateRoot('/dashboard');
          }, error => {
            this.loading.dismiss();
            this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
          });
      } else if (this.selectedReference !== 5) {
        this.loadingCtrl.create().then((overlay) => {
          this.loading = overlay;
          this.loading.present();
        });

        this.ichambaService.addHero(this.name, this.categories_rearranged.join(','), (this.keywords_string.join(', ') == "" ? null : this.keywords_string.join(', ')), this.myAddress, this.myPosition.latitude, this.myPosition.longitude, this.selectedReference, this.reference).subscribe(
          data => {
            this.loading.dismiss();
              this.alertService.presentToast(data['message']);
              this.navCtrl.navigateRoot('/dashboard');
          }, error => {
            this.loading.dismiss();
            this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
          });
      } else {
        this.alertService.presentToast("Por favor, específique cómo supo de nosotros");
      }
    } else {
      this.alertService.presentToast("Llene todos los datos solicitados");
    }
  }

  showlist() {
    this.showif = true;
  }

  hidelist() {
    this.showif = false;
  }

}
