import { Injectable } from '@angular/core';
import { Http, Headers,RequestOptions } from '@angular/http';
import { EcmLocation } from './ecm-location';
import { EventEmitter } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppState } from '../ecm-store/reducers';
import { LocationActions } from '../ecm-store/actions/location';

@Injectable()
export class EcmLocationService {

    constructor( public http: Http, private store: Store<AppState>, private locationAction:LocationActions) {}
    
    find(nameKey, myArray){   
      for (var i=0; i < myArray.length; i++) { 
        if (myArray[i].types[0] === nameKey) {
            return myArray[i];
        }
      }
    }

    getGeoLocation() {
      let localCity = localStorage.getItem('city');
      
      if([null, undefined, ""].indexOf(localCity,0) != -1) {
      
      		//navigator.geolocation.getCurrentPosition(this.successCallback,this.errorCallback,this.options);
      		//https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyBo62AVqqkEz5Ys9D-dQWE_VF4lVpHaFy0
      		let headers = new Headers({ 'Content-Type': 'application/json' });
      		let options = new RequestOptions({ headers: headers });
      		this.http.post('https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyBo62AVqqkEz5Ys9D-dQWE_VF4lVpHaFy0',options).subscribe(
          		response => {
              		if(response.status == 200){
              		    let data = response.json();               
              		    console.log('geolocate -- data.......'+ JSON.stringify(data) );   
              		    console.log("the respective location data id"+data);
              		    this.displayLocation(data);
              		}
      	  		},
          		error => {
         			alert(error.text());
      			}
      		);
      } else {
          // do something when you already have the location
      }
    }

    errorCallback = (error) => {
            let errorMessage = 'Unknown error';
            switch(error.code) {
              case 1:
                errorMessage = 'Permission denied';
                break;
              case 2:
                errorMessage = 'Position unavailable';
                break;
              case 3:
                errorMessage = 'Timeout';
                break;
            }
            console.log(errorMessage);
    };

    options = {
            enableHighAccuracy: true,
            timeout: 1000,
            maximumAge: 0
    }; 

    displayLocation = (position) => {

      let ecmLocation : EcmLocation = new EcmLocation();
      ecmLocation.latitude = position.location.lat;
      ecmLocation.longitude = position.location.lng;

      this.http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng='+position.location.lat+','+position.location.lng+'&sensor=true').subscribe(
          response => {
              if(response.status == 200){
                  let data = response.json();
                  //this.loc_data=data;
                  console.log('geocode -- data.......'+JSON.stringify(data));             
                  console.log('geocode -- data keys.......'+Object.keys(data));             
                  if(data)
                  {
                   var resultObject = this.find("locality", data.results[0].address_components);
                   //this.city = resultObject.long_name;
                   
                   ecmLocation.city = resultObject.long_name;
                   //this.add = data.results[0].formatted_address;
                   ecmLocation.address =  data.results[0].formatted_address;
                   ecmLocation.state = data.results[0].address_components[7].long_name;
                   ecmLocation.country = data.results[0].address_components[8].long_name;
                   ecmLocation.pincode = data.results[0].address_components[9].long_name;
                   console.log("----------"); 
                   console.log("start of a resultObject"+JSON.stringify(resultObject))
                   console.log("----------");  
                  }   

                  //this.store.dispatch(this.locationAction.resetBlankLocation());
                  this.store.dispatch(this.locationAction.getLocationSuccess(ecmLocation));

                  //EmitterService.get("selectedLocation").emit(ecmLocation);                 
                  //localStorage.setItem('mycity',this.city);                  
                  // console.log(data.results[0].formatted_address);
                   //console.log(this.add);
              }
              //localStorage.setItem('location', JSON.stringify(location));
              //EmitterService.get("selectedCity").emit(location['city']);
          },
          error => {
           alert(error.text());
          }
      );
    }
    
}
/*

@Injectable()
export class EmitterService {
  private static _emitters: { [channel: string]: EventEmitter<any> } = {};
  
  static get(channel: string): EventEmitter<any> {
    if (!this._emitters[channel])
      this._emitters[channel] = new EventEmitter();
    return this._emitters[channel];
  }
}

*/