package com.example.Maps013;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.json.JSONObject;

import android.location.Address;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.Toast;

//import com.google.android.gms.identity.intents.Address;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import com.google.android.gms.maps.model.LatLng;

public class Geo04 extends Activity 
{

	AutoCompleteTextView atvPlaces;
	PlacesTask placesTask;
	ParserTask parserTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
			super.onCreate(savedInstanceState);
			setContentView(R.layout.geo04_layout);
			
			atvPlaces = (AutoCompleteTextView) findViewById(R.id.myautocomplete);
			atvPlaces.setThreshold(2);		
			
			atvPlaces.addTextChangedListener(new TextWatcher() 
			{
				
					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) 
					{				
						placesTask = new PlacesTask();				
						placesTask.execute(s.toString());
						//placesTask.execute("paris");
					}
					
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count,	int after)
					{
						// TODO Auto-generated method stub
					}
					
					@Override
					public void afterTextChanged(Editable s) 
					{
						// TODO Auto-generated method stub				
					}
			});	
	}
	
	
    private String downloadUrl(String strUrl) throws IOException
    {
	        String data = "";
	        InputStream iStream = null;
	        HttpURLConnection urlConnection = null;
	        try
	        {
	                URL url = new URL(strUrl);                
	
	                urlConnection = (HttpURLConnection) url.openConnection();
	
	                urlConnection.connect();
	
	                // Reading data from url 
	                iStream = urlConnection.getInputStream();
	
	                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
	                StringBuffer sb  = new StringBuffer();
	
	                String line = "";
	                while( ( line = br.readLine())  != null)
	                {
	                        sb.append(line);
	                }
	                
	                data = sb.toString();
	                br.close();
	        }
	        catch(Exception e)
	        {
	                Log.d("Exception while downloading url", e.toString());
	        }
	        finally
	        {
	                iStream.close();
	                urlConnection.disconnect();
	        }
	        return data;
     }	
	
	// Fetches all places from GooglePlaces AutoComplete Web Service
	private class PlacesTask extends AsyncTask<String, Void, String>
	{

		@Override
		protected String doInBackground(String... place)
		{
			
			String data = "";
			
			// Obtain browser key from https://code.google.com/apis/console
			String key = "AIzaSyBXw9vydHGGjBOYSeM9i-Xh8f9Mk0xzg1k";
			
			String input="";
			
			try {
				input = "input=" + URLEncoder.encode(place[0], "utf-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}		
			
			// place type to be searched
			String types = "types=geocode";
			
			// Sensor enabled
			String sensor = "sensor=false";			
			
			// Building the parameters to the web service
			  String parameters = input+"&"+types+"&"+sensor+"&key="+key;
			  parameters = input+"&"+types+"&"+sensor+"&key="+key+"&components=country:FR";
			  
			//String parameters = input+"&"+types+"&"+sensor+"&"+key+"&components=country:FR";
			
			//Change input+”&”+types+”&”+sensor+”&”+key; ==> input+”&”+types+”&”+sensor+”&key=”+key;
			
			// Output format
			String output = "json";
			
			// Building the url to the web service
			String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
			
			//url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&key=AIzaSyBXw9vydHGGjBOYSeM9i-Xh8f9Mk0xzg1k";
	
			try
			{
				// Fetching the data from web service in background
				data = downloadUrl(url);
			}
			catch(Exception e)
			{
                Log.d("Background Task",e.toString());
			}
			
			return data;		
			
			//  "error_message" : "This API project is not authorized to use this API. Please ensure this API is activated in the Google Developers Console: https://console.developers.google.com/apis/api/places_backend?project=_",   "predictions" : [],   "status" : "REQUEST_DENIED"}
		}
		
		@Override
		protected void onPostExecute(String result) 
		{			
				super.onPostExecute(result);
				
				// Creating ParserTask
				parserTask = new ParserTask();
				
				// Starting Parsing the JSON string returned by Web Service
				parserTask.execute(result);
		}		
	}
	
	
	/** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>
    {

    		JSONObject jObject;
    	
    		@Override
    		protected List<HashMap<String, String>> doInBackground(String... jsonData) 
    		{			
			
    			List<HashMap<String, String>> places = null;
			
    			PlaceJSONParser placeJsonParser = new PlaceJSONParser();
            
    			try
    			{
    				jObject = new JSONObject(jsonData[0]);
            	
    				// Getting the parsed data as a List construct
    				places = placeJsonParser.parse(jObject);

    			}
    			catch(Exception e)
    			{
            	Log.d("Exception",e.toString());
    			}
            return places;
    		}
		
    		@Override
    		protected void onPostExecute(List<HashMap<String, String>> result)
    		{			
			
				String[] from = new String[] { "description"};
				int[] to = new int[] { android.R.id.text1 };
				
				// Creating a SimpleAdapter for the AutoCompleteTextView			
				SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);				
				
				// Setting the adapter
				atvPlaces.setAdapter(adapter);
    		}			
    }    
    
	
}
 
