package com.manubet.android.touristAndroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import android.util.Log;


public class GeoCoding {
	
	public static String toDirection(double lat, double lon) {
		URL url=null;
		StringBuilder builder;
		String pais=null;
		boolean paisEnc=false;
		int jsonIndex=3;
		JSONObject primero=null;
		try {
			url = new URL("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true");
		} catch (MalformedURLException e) {
			InfoProvider.country="EN";
			return lat+","+lon;
		}
		//Log.d("GEOCODE",url.toString());
		
		// conexion con GeoCode
		

		URLConnection connection;
		try {
			connection = url.openConnection();
			connection.setConnectTimeout(000); 
			connection.setReadTimeout(1000);
			connection.addRequestProperty("Referer","http://touristdroid.blogspot.com/");
			String line;
			builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			while((line = reader.readLine()) != null) {
				builder.append(line);
			}
		}catch (IOException e) {
			InfoProvider.country="EN";
			return lat+","+lon;
		}

		JSONObject json;
		JSONArray results = null;
		try {
			json = new JSONObject(builder.toString());
			results= json.getJSONArray("results");
		} catch (JSONException e1) {
			InfoProvider.country="EN";
			return lat+","+lon;
		} //resultado entero
		
		try {
		 primero = results.getJSONObject(0);
		}
		catch (JSONException e){
			InfoProvider.country="EN";
			return lat+","+lon;
		}
		JSONArray add_comp;
		try {
			add_comp = primero.getJSONArray("address_components");
		} catch (JSONException e) {
			InfoProvider.country="EN";
			return lat+","+lon;
		}
		
		String street_number;
		try {
			street_number = add_comp.getJSONObject(0).getString("long_name");
		} catch (JSONException e) {
			street_number="";
		}
		
	
		String street;
		try {
			street = add_comp.getJSONObject(1).getString("long_name");
		} catch (JSONException e) {
			street="";
		}
		String city;
		try {
			city = add_comp.getJSONObject(2).getString("long_name");
		} catch (JSONException e) {
			city="";
		}
		//Log.d("DECODER",street+","+street_number+","+city);
		
		
		while(jsonIndex<add_comp.length()&!paisEnc){ //pais
			JSONObject aux;
			try {
				aux = add_comp.getJSONObject(jsonIndex);
			
			JSONArray aux1=aux.getJSONArray("types");
			//Log.d("JSON",aux1.getString(0)+"");
			if(aux1.getString(0).equals("country")){
				
				pais=aux.getString("short_name");
				paisEnc=true;
			}
			} catch (JSONException e) {
				continue;
			}
			jsonIndex++;  
		}
		if(pais==null){
			pais="EN";
		}
		//Log.d("PAIS",pais);
		InfoProvider.country=pais;


		
	return street+","+street_number+","+city;	
	}

}
