import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { WpServiceService } from '../wp-service.service';

import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NativeGeocoder, NativeGeocoderResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';

declare var google;

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

  data: any;
  placelist: any;

  @ViewChild('map', { static: false }) mapElement: ElementRef;
  map: any;
  address: string;
  latitude: number;
  longitude: number;
  latdynamic: any;
  londynamic: any;
  

  constructor(private wpservice: WpServiceService, private route: ActivatedRoute, private router: Router, private geolocation: Geolocation, private nativeGeocoder: NativeGeocoder) { }
  @Input() id: string;
  showDiss = false;


  ngOnInit() {
    if (this.id != undefined) {
      this.showDiss = true;
    }
    this.loadMap();
    // console.log("showDiss ", this.showDiss);
    // let id = this.route.snapshot.paramMap.get('id') || this.id;
    // console.log("fetching ...");
    // this.wpservice.getPlaceDetail(id).subscribe(data => {
    // let post = JSON.parse(data.data);
    // console.log(" get data ", post);
    // post['media_url'] = post['_embedded']['wp:featuredmedia'][0]['media_details'].sizes['medium'].source_url;
    // this.data = post;
    let id = this.route.snapshot.paramMap.get('id') || this.id;
    console.log("fetching ...");
    this.wpservice.getPlaceDetail(id).subscribe((data) => {
      this.placelist = data;
      this.latdynamic = data['acf']['gmap']['lat'];
      this.londynamic = data['acf']['gmap']['lng'];
      console.log("load Place Detail ...");
      console.log(this.latdynamic);
      console.log("load Lati ...");
      console.log(this.londynamic);
      console.log("load Lon ...");
      console.log(data);
    }, error => {
      console.log("errror ", error);
    });
  }

  loadMap() {
    this.geolocation.getCurrentPosition().then((resp) => {

      this.latitude = resp.coords.latitude;
      this.longitude = resp.coords.longitude;
      // this.latdynamic = resp.coords.latitude;
      // this.londynamic = resp.coords.longitude;

      let latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }

      this.getAddressFromCoords(resp.coords.latitude, resp.coords.longitude);

      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

      this.map.addListener('dragend', () => {

        this.latitude = this.map.center.lat();
        this.longitude = this.map.center.lng();

        this.getAddressFromCoords(this.map.center.lat(), this.map.center.lng())
      });

    }).catch((error) => {
      console.log('Error getting location', error);
    });
  }

  getAddressFromCoords(lattitude, longitude) {
    console.log("getAddressFromCoords " + lattitude + " " + longitude);
    let options: NativeGeocoderOptions = {
      useLocale: true,
      maxResults: 5
    };

    this.nativeGeocoder.reverseGeocode(lattitude, longitude, options)
      .then((result: NativeGeocoderResult[]) => {
        this.address = "";
        let responseAddress = [];
        for (let [key, value] of Object.entries(result[0])) {
          if (value.length > 0)
            responseAddress.push(value);

        }
        responseAddress.reverse();
        for (let value of responseAddress) {
          this.address += value + ", ";
        }
        this.address = this.address.slice(0, -2);
      })
      .catch((error: any) => {
        this.address = "Address Not Available!";
      });

  }

  // getAddressFromCoords2(lattitude, longitude) {
  //   console.log("getAddressFromCoords2 " + lattitude + " " + longitude);
  //   let options: NativeGeocoderOptions = {
  //     useLocale: true,
  //     maxResults: 5
  //   };
  // }

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