package com.example.geo_api10;

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.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity 
{

	AutoCompleteTextView atvPlaces;
	AutoCompleteTextView arrivalPlaces;
	
	autocomplete_PlacesTask autocomplete_PlacesTask;
	autocomplete_ParserTask autocomplete_ParserTask;
	    
	PlacesTask_departure placesTask_departure;
	ParserTask_departure parserTask_departure;
		
	PlacesTask_destination placesTask_destination;
	ParserTask_destination parserTask_destination;
	

	GoogleMap map;
	
	AutoCompleteTextView depart;
	AutoCompleteTextView arrive;
	
	String departure = "";
	String arrival = "";

	
	/*************************/
	
	//GoogleMap googleMap;
	

	ArrayList markerPoints;
	Dialog dialog;
	AlertDialog.Builder alertDialog;
	EditText et_departure, et_destination;
	Button btn_find, btn_cancel, btn_direction;
	String test_message_address_departure = "";
	String test_message_address_destination = "";
	boolean flag_address_departure = true;
	boolean flag_address_destination = true;
	int test_sequence = 0;
	TextView tvDistanceDuration;
	
	private ProgressDialog progressdialog;
	ArrayList<String> names;
    JSONObject json;
    String url;
  
    ArrayAdapter<String> adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	
		init();
		
	}
	
	/************************************ AUTOCOMPLETE ***********************************************************/
		
	public void init()
	{
			SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map); 
				
			map = mapFragment.getMap();
				
		
		    depart = (AutoCompleteTextView) findViewById(R.id.departure_places);
	        depart.setThreshold(5);
	        
	        arrive = (AutoCompleteTextView) findViewById(R.id.arrival_places);
	        arrive.setThreshold(5);
	        
	        depart.addTextChangedListener(new TextWatcher()
	        {
	        	 
		            @Override
		            public void onTextChanged(CharSequence s, int start, int before, int count)
		            {
		            	placesTask_departure = new PlacesTask_departure();
		            	placesTask_departure.execute(s.toString());
		            }
		 
		            @Override
		            public void beforeTextChanged(CharSequence s, int start, int count, int after)
		            {
		                
		            }
		 
		            @Override
		            public void afterTextChanged(Editable s) 
		            {
		              
		            }
	        });
	        
	        arrive.addTextChangedListener(new TextWatcher()
	        {
	        	 
		            @Override
		            public void onTextChanged(CharSequence s, int start, int before, int count)
		            {
		            	placesTask_destination = new PlacesTask_destination();
		            	placesTask_destination.execute(s.toString());
		            }
		 
		            @Override
		            public void beforeTextChanged(CharSequence s, int start, int count, int after)
		            {
		                
		            }
		 
		            @Override
		            public void afterTextChanged(Editable s) 
		            {
		              
		            }
	        });
	        
	        
	    	btn_direction = (Button) findViewById(R.id.btn_calculation);
	    	btn_direction.setOnClickListener(new View.OnClickListener() 
            {
                    @Override
                    public void onClick(View v) 
                    {
                    	Toast.makeText(getApplicationContext(), "Calculation ...", Toast.LENGTH_LONG).show();
                    	
                    		if (depart.getText().toString().isEmpty() || arrive.getText().toString().isEmpty())
	                        {
	                            Toast.makeText(getApplicationContext(), "Text fields cannot be empty", Toast.LENGTH_SHORT).show();
	                        } 
	                        else 
	                        {
	                        	//map.clear();
	                        	
	                        	departure = depart.getText().toString();
	                        	arrival = arrive.getText().toString();
	                        	
	                        	ArrayList<String> list=new ArrayList<String>();  
	                        	list.add(departure);  
	                        	list.add(arrival);  
	                        	
	                        	String concatenate = departure + " " + arrival;
	                        	
	                        	Toast.makeText(getApplicationContext(), concatenate , Toast.LENGTH_SHORT).show();
	                        	
	                        	String url = "https://maps.googleapis.com/maps/api/geocode/json?";					
	            				
	            				try 
	            				{
	            					departure = URLEncoder.encode(departure, "utf-8");
	            				} 
	            				catch (UnsupportedEncodingException e)
	            				{
	            					e.printStackTrace();
	            				}
	            				
	            				String address = "address=" + departure;
	            				String sensor = "sensor=false";
	            				url = url + address + "&" + sensor;
	            				aaaDownloadTask aaadownloadTask = new aaaDownloadTask();
	            				aaadownloadTask.execute(url);
	                        	
	                        }	
                    	
                    }
            });
				
	
	}
	
	
	
	private String downloadUrl_departure(String strUrl) throws IOException
	{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);                

                // Creating an http connection to communicate with url 
                urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                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;
     }	
	
		private class PlacesTask_departure extends AsyncTask<String, Void, String>{

			@Override
			protected String doInBackground(String... place) {
				// For storing data from web service
				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";

				//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_departure(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_departure = new ParserTask_departure();
				
				// Starting Parsing the JSON string returned by Web Service
				parserTask_departure.execute(result);
			}		
		}
	
	
		/** A class to parse the Google Places in JSON format */
	    private class ParserTask_departure 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
					depart.setAdapter(adapter);
			}			
	    }    
	
	
	    private String autocomplet_downloadUrl(String strUrl) throws IOException
	    {
	        String data = "";
	        InputStream iStream = null;
	        HttpURLConnection urlConnection = null;
	        try{
	                URL url = new URL(strUrl);                

	                // Creating an http connection to communicate with url 
	                urlConnection = (HttpURLConnection) url.openConnection();

	                // Connecting to url 
	                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 autocomplete_PlacesTask extends AsyncTask<String, Void, String>
		{

			@Override
			protected String doInBackground(String... place) {
				// For storing data from web service
				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;
				parameters = input+"&"+types+"&"+sensor+"&key="+key+"&components=country:FR";
				//String parameters = input+"&"+types+"&"+sensor+"&"+key+"&components=country:fr";
				
				
				//&components=country
				
				// Output format
				String output = "json";
				
				// Building the url to the web service
				String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
		
				try{
					// Fetching the data from web service in background
					data = autocomplet_downloadUrl(url);
				}catch(Exception e){
	                Log.d("Background Task",e.toString());
				}
				return data;		
			}
			
			@Override
			protected void onPostExecute(String result) {			
				super.onPostExecute(result);
				
				// Creating ParserTask
				autocomplete_ParserTask = new autocomplete_ParserTask();
				
				// Starting Parsing the JSON string returned by Web Service
				autocomplete_ParserTask.execute(result);
			}		
		}
	
	
		 /** A method to download json data from url */
	    private String downloadUrl_destination(String strUrl) throws IOException{
	        String data = "";
	        InputStream iStream = null;
	        HttpURLConnection urlConnection = null;
	        try{
	                URL url = new URL(strUrl);                

	                // Creating an http connection to communicate with url 
	                urlConnection = (HttpURLConnection) url.openConnection();

	                // Connecting to url 
	                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;
	     }	
		
	
		/** A class to parse the Google Places in JSON format */
	    private class autocomplete_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
					depart.setAdapter(adapter);
			}			
	    }    
	
	
	 // Fetches all places from GooglePlaces AutoComplete Web Service
		private class PlacesTask_destination extends AsyncTask<String, Void, String>{

			@Override
			protected String doInBackground(String... place) {
				// For storing data from web service
				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";

				//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_destination(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_destination = new ParserTask_destination();
				
				// Starting Parsing the JSON string returned by Web Service
				parserTask_destination.execute(result);
			}		
		}
		
	
		/** A class to parse the Google Places in JSON format */
	    private class ParserTask_destination 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
					arrive.setAdapter(adapter);
			}			
	    }    
	
	
	
	
	/*****************************************************************************************************/
	
    
	    private String aaadownloadUrl(String strUrl) throws IOException{
	        String data = "";
	        InputStream iStream = null;
	        HttpURLConnection urlConnection = null;
	        try{
	                URL url = new URL(strUrl);


	                // Creating an http connection to communicate with url 
	                urlConnection = (HttpURLConnection) url.openConnection();

	                // Connecting to url 
	                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;
	        
		}


	

	    private class aaaDownloadTask extends AsyncTask<String, Integer, String>{

	            String data = null;

	            // Invoked by execute() method of this object
	            @Override
	            protected String doInBackground(String... url) {
	                    try{                    		
	                            data = aaadownloadUrl(url[0]);
	                    }catch(Exception e){
	                             Log.d("Background Task",e.toString());
	                    }
	                    return data;
	            }

	            // Executed after the complete execution of doInBackground() method
	            @Override
	            protected void onPostExecute(String result){
	            		
	            		// Instantiating ParserTask which parses the json data from Geocoding webservice
	            		// in a non-ui thread
	            		aaaParserTask aaaparserTask = new aaaParserTask();

	                    // Start parsing the places in JSON format
	                    // Invokes the "doInBackground()" method of the class ParseTask
	                    aaaparserTask.execute(result);
	            }

	    }
	


	    class aaaParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>
		{

			JSONObject jObject;
			
			// Invoked by execute() method of this object
			@Override
			protected List<HashMap<String,String>> doInBackground(String... jsonData)
			{
			
				List<HashMap<String, String>> places = null;			
				GeocodeJSONParser parser = new GeocodeJSONParser();
	        
		        try{
		        	jObject = new JSONObject(jsonData[0]);
		        	
		          
		            places = parser.parse(jObject);
		            
		        }catch(Exception e){
		                Log.d("Exception",e.toString());
		        }
		        return places;
			}
			
		
			@Override
			protected void onPostExecute(List<HashMap<String,String>> list)
			{			
				
				// Clears all the existing markers			
				//mMap.clear();
				
				for(int i=0;i<list.size();i++)
				{
				
					// Creating a marker
		            MarkerOptions markerOptions = new MarkerOptions();
		            
		            // Getting a place from the places list
		            HashMap<String, String> hmPlace = list.get(i);
		
		            // Getting latitude of the place
		            double lat = Double.parseDouble(hmPlace.get("lat"));	            
		            
		            // Getting longitude of the place
		            double lng = Double.parseDouble(hmPlace.get("lng"));
		            
		            // Getting name
		            String name = hmPlace.get("formatted_address");
		            
		            LatLng latLng = new LatLng(lat, lng);
		            
		            // Setting the position for the marker
		            markerOptions.position(latLng);
		            
		            // Setting the title for the marker
		            markerOptions.title(name);
		
		            // Placing a marker on the touched position
		            map.addMarker(markerOptions);    
		            
		            // Locate the first location
	                if(i==0)
	                	map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
	            }            
			}
		}
	

	

	
}