import { Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult } from '@ionic-native/native-geocoder/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NgForm } from '@angular/forms';
import { AuthService } from './../../config/auth.service';
import { Address } from './../../config/services/user';


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

  geoLatitude: number;
  geoLongitude: number;
  geoAccuracy: number;
  geoAddress: string;
  address: Address  = {
    addressType: '',
    area: '',
    city: '',
    country: '',
    district: '',
    firstAddress: '',
    landmark: '',
    zip: '',
    secondAddress: '',
    state: '',
    default: 0
  };
  submitted = false;

  geoencoderOptions: NativeGeocoderOptions = {
    useLocale: true,
    maxResults: 5
  };

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private location: Location,
    private geolocation: Geolocation,
    private nativeGeocoder: NativeGeocoder,
    private register: AuthService
  ) { }

  ngOnInit() {
    
  }

  goToPage(path, data = null) {
    this.router.navigateByUrl(path, { queryParams: data });
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  goBack() {
    this.location.back();
  }

  getGeolocation() {
    console.log('getLocation');
    this.geolocation.getCurrentPosition().then(pos => {
      console.log('get New location');
      console.log(pos);
      this.geoLatitude = pos.coords.latitude;
      this.geoLongitude = pos.coords.longitude;
      this.geoAccuracy = pos.coords.accuracy;
      this.getGeoencoder(this.geoLatitude, this.geoLongitude);
    }).catch(err => {
      alert('Error getting location' + JSON.stringify(err));
    });
  }

  getGeoencoder(latitude, longitude) {
    console.log('reached');
    this.nativeGeocoder.reverseGeocode(latitude, longitude, this.geoencoderOptions)
    .then((result: NativeGeocoderResult[]) => {
      console.log(result);
      this.geoAddress = this.generateAddress(result[0]);
      console.log(this.geoAddress);
    })
    .catch((error: any) => {
      alert('Error getting location' + JSON.stringify(error));
    });
  }

  generateAddress(addressObj) {
    const obj = [];
    let address = '';
    // tslint:disable-next-line:forin
    for (const key in addressObj) {
      obj.push(addressObj[key]);
    }
    obj.reverse();
    for (const val in obj) {
      if (obj[val].length) {
      address += obj[val] + ', ';
      }
    }
    return address.slice(0, -2);
}

onAddrss(form: NgForm) {
  this.submitted = true;
  console.log(form.value);
  if (form.valid) {
    console.log(form.value);
    this.register.createAddress(form.value);
  } else {
    console.log(form.errors);
  }
}

}
