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 java.util.LinkedList;



import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
//import android.util.Log;
import android.widget.Toast;

public class InfoProvider { 
	private static LinkedList<Place> places = new LinkedList<Place>();
	private JSONObject json=null;;
	URL url=null;
	static String country;
	Context mContext;
	private SharedPreferences preferences;
	private String autoIdi="AUTO";
 
	public InfoProvider(Context context){
		mContext=context;
        preferences = PreferenceManager.getDefaultSharedPreferences(context);
      	}
	
	public boolean updatePlaces(double lat, double lng)  {
		boolean correcto=false;
		int cont=0;
		JSONArray resultado = new JSONArray();
		//dada una direccion, hago una consulta
        autoIdi=preferences.getString("idi", "AUTO");
        if(!autoIdi.equals("AUTO")){
        	country=preferences.getString("idi", country);
        }
		StringBuilder responseBuilder = new StringBuilder();
		
		while(!correcto & cont<3) {
	///////////////////////////////////////////URL, no debe fallar
		try { 
			//Log.d("wiki","http://ws.geonames.org/findNearbyWikipediaJSON?lat="+lat+"&lng="+lng+"&lang="+country.toLowerCase()+"&maxRows=20&radius=20");
			url = new URL("http://ws.geonames.org/findNearbyWikipediaJSON?lat="+lat+"&lng="+lng+"&lang="+country.toLowerCase()+"&maxRows=20&radius=20");
		} catch (MalformedURLException e) {
			Toast.makeText(mContext, R.string.error_proveedor, Toast.LENGTH_SHORT).show();
			continue;
		}
	///////////////////////////////////////conexion, fallo de conexion
		URLConnection connection;
		try {
			connection = url.openConnection();
			connection.setConnectTimeout(2000);
		} catch (IOException e1) { 
			Toast.makeText(mContext, R.string.error_conexion, Toast.LENGTH_SHORT).show();
			cont++;
			continue;
		}
	//////////////////////////////recepcion, fallo en la respuesta
		String line; 
	    BufferedReader in;
		try {
			in = new BufferedReader(new InputStreamReader (url.openStream()));
		    while ((line = in.readLine()) != null) {
	            responseBuilder.append(line);
	        } 
	        in.close();
	        //Log.d("wiki","conexion finalizada");
		} catch (IOException e1) { 
			
			cont++;
			Toast.makeText(mContext, R.string.error_recepcion, Toast.LENGTH_SHORT).show();
			continue;
		}
		
		///////////////////////////conversion a JSON
        
        try {
       	 json = new  JSONObject(responseBuilder.toString());
       	 //Log.d("wiki","datos recibidos");
       } catch (JSONException e) {
    	   cont++;
           continue;
       }
       try {
			resultado=json.getJSONArray("geonames");
			//Log.d("JSON", json.toString());//JSON orginal

		} catch (JSONException e) { //error en la conversion, causas desconocidas
			cont++;
			continue;
		}
		if(resultado.length()>0 ){ //hay resultados--->procesar
			correcto=true;
			//Log.d("PROVIDER","mayor que cero");
			this.processPlaces(resultado,lat,lng);
			}
		else{
			country="EN";
			cont++;
	        responseBuilder = new StringBuilder();
	        url=null;
	        json=null;
	        //resultado=null;
		}

		//dos opciones:
		//- todo bien: correcto=true y se ha llamado a processPlaces()
		//- algo fallo: correcto sigue siendo falso, si cont<3 se vuelve a intentar
		}


		return correcto;
	}
			
	private void processPlaces(JSONArray result, double lat, double lng)  {
		JSONObject aux=null;
		getPlaces().clear();
		String thumb, summary;

		//Log.d("size","tamaņo: "+ result.length());
		for (int i=0;i<result.length();i++){
			try {
				aux=result.getJSONObject(i);
			} catch (JSONException e) {
				continue;
			}
			try {
				thumb=aux.getString("thumbnailImg");}
			catch (JSONException j){
				thumb="";
			}
			try {
				summary = aux.getString("summary");
			} catch (JSONException e1) {
				summary="";
			}
			
			try {
				getPlaces().add(new Place( aux.getString("title"),
						   Double.valueOf(aux.getString("lat")).doubleValue(),
						   Double.valueOf(aux.getString("lng")).doubleValue(),
						   thumb,
						   aux.getString("wikipediaUrl"),
						   summary
						   ));
			} catch (NumberFormatException e) {
				continue;
			} catch (JSONException e) {
				continue;
			}
		}
	}

	public static void setPlaces(LinkedList<Place> places) {
		InfoProvider.places = places;
	}

	public static LinkedList<Place> getPlaces() {
		return places;
	}
}
