import { Component, OnInit, NgZone } from '@angular/core';
import { NavController, LoadingController } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
import { AuthService } from 'src/app/services/auth.service';
import { AlertService } from 'src/app/services/alert.service';
import { IchambaService } from 'src/app/services/ichamba.service';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { TranslateService } from '@ngx-translate/core';
import { GoogleMaps, GoogleMap, GoogleMapsEvent, LatLng, MarkerOptions, Geocoder, GeocoderRequest, GeocoderResult } from '@ionic-native/google-maps';

declare var google: any;

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

  private loading;
  category = null;
  //money: number = null;
  //amount: number = null;
  //amount_check = true;
  minyear: string = (new Date().getFullYear() + '-' +  ((new Date().getMonth() + 1) < 10 ? '0' : '') + (new Date().getMonth() + 1) + '-' + (new Date().getDate() < 10 ? '0' : '') + new Date().getDate()).toString();
  maxyear: string = null;
  mintime: number;
  maxtime: number;
  setHour: any;
  setDate: any;
  references: string;
  details: string;
  differenceDate: number;
  differenceHour: number;
  myPosition: any = {};
  myAddress: string = null;
  myIntnumber: string = null;
  addressAutocomplete: string = '';
  placesSearch: string = '';
  showif = true;

  constructor(
    private authService: AuthService,
    private navCtrl: NavController,
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private activatedRoute: ActivatedRoute,
    private geolocation: Geolocation,
    private translateService: TranslateService,
    private googleMaps: GoogleMaps,
    private geocoder: Geocoder,
    private locaccuracy: LocationAccuracy,
    private ngZone: NgZone,
    private loadingCtrl: LoadingController
  ) {
    console.log(google);
  }

  ngOnInit() {
    this.category = this.activatedRoute.snapshot.paramMap.get('category');
    this.ichambaService.getParameters()
      .subscribe( data => {
        this.mintime = data['min_time'];
        this.maxtime = data['max_time'];
      });
    this.getCurrentLocation();
    console.log(this.minyear);
    if (new Date().getMonth() == 11) {
        this.maxyear = ((new Date().getFullYear()+1) + '-' + '01' + '-' + (new Date().getDate() < 10 ? '0' : '') + new Date().getDate()).toString();
    } else {
      this.maxyear = (new Date().getFullYear() + '-' + ((new Date().getMonth() + 2) < 10 ? '0' : '') + (new Date().getMonth() + 2) +'-' + (new Date().getDate() < 10 ? '0' : '') + new Date().getDate()).toString();
    }
    console.log(this.maxyear);
  }

  getCurrentLocation() {
        this.locaccuracy.request(this.locaccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(() => {
          this.geolocation.getCurrentPosition({ maximumAge: 20000, timeout: 30000, enableHighAccuracy: true }).then((resp) => {
            console.log(resp);
            this.myPosition = {
              latitude: resp.coords.latitude,
              longitude: resp.coords.longitude
            }
            this.doGeocode();
          }).catch((error) => {
            console.log(this.translateService.instant('alerts.geo_error') + error);
          });
        }, (error) => {
          console.log(error);
        });
  }

  doGeocode() {
   let request: GeocoderRequest = {
     position: new LatLng(this.myPosition.latitude, this.myPosition.longitude),
   };
   this.geocoder.geocode(request)
   .then((results: GeocoderResult[]) => {
     let address = [
       (results[0].thoroughfare || "") + " " + (results[0].subThoroughfare || ""),
       results[0].locality
     ].join(", ");
     console.log("data_: ", address);
     this.myAddress = address;
   });
  }

  /* check (ev: any) {
    this.amount = parseFloat(ev.target.value.replace(",", ""));
    console.log(this.amount);
    if (this.amount < 150) {
      this.amount_check = false;
    } else {
      this.amount_check = true;
    }
  }*/

  changehour (ev: any) {
    console.log(this.setHour);
  }

  changedate (ev: any) {
    console.log(ev.target.value);
    let current_date = (new Date().toISOString().slice(0, 10)).toString();
    let selected_date = (new Date(this.setDate).toISOString().slice(0, 10)).toString();
    this.differenceDate = (Number(new Date(selected_date)) - Number(new Date(current_date)));
    console.log(this.differenceDate);
  }

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

  addpostulation() {
    this.differenceHour = (new Date(this.setHour).getTime() - new Date().getTime());
    console.log(this.differenceHour);
    console.log("mintime:" + this.mintime * 3600000);
    console.log("maxtime:" + this.maxtime * 3600000)
    if (this.differenceDate < 86400000 && this.differenceHour < (this.mintime * 3600000)) {
      this.alertService.presentToast(this.translateService.instant('alerts.categories_mintime'));
    } else if (this.differenceDate <= (this.maxtime * 3600000)) {
        if (this.myAddress && this.myPosition.latitude && this.myPosition.longitude) {
            this.loadingCtrl.create().then((overlay) => {
              this.loading = overlay;
              this.loading.present();
            });

            if (!Number.isInteger(parseInt(this.myIntnumber))) {
              this.myIntnumber = null;
            }
            this.ichambaService.addPostulation(this.category, this.myAddress, this.myIntnumber, this.references, this.myPosition.latitude, this.myPosition.longitude, this.setDate, this.setHour, this.details).subscribe(
              data => {
                this.loading.dismiss();
                if (data['message'] == 'No providers') {
                  this.alertService.presentToast(this.translateService.instant('alerts.no_provider'));
                } else {
                  this.navCtrl.navigateRoot('/dashboard');
                  this.alertService.presentToast(this.translateService.instant('alerts.categories_success'));
                }
              }, error => {
                this.loading.dismiss();
                this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
              });
        } else {
          this.alertService.presentToast(this.translateService.instant('alerts.valid_address'));
        }
    } else {
      this.alertService.presentToast(this.translateService.instant('alerts.categories_maxtime'));
    }
  }

  showlist() {
    this.showif = true;
  }

  hidelist() {
    this.showif = false;
  }

}
