package com.example.Maps010;

import java.io.IOException;
import java.util.List;

import com.google.android.gms.identity.intents.Address;

import android.app.Activity;
import android.location.Geocoder;
import android.os.Bundle;

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.HashMap;
import java.util.List;
 
import org.json.JSONObject;
 
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
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;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
// directions
//http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/
// http://www.androidtrainee.com/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/
// https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/
// http://www.coderzheaven.com/2016/01/27/starting-with-google-maps-v2-in-android-simple-implementation/
// http://javapapers.com/android/draw-path-on-google-maps-android-api/

// add markers
// http://android-er.blogspot.fr/2015/10/add-marker-to-google-map-google-maps.html


//  ****************  a voir
//http://www.androidtrainee.com/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/

// Get directions from Google Map V2 providing address
public class Geo01 extends FragmentActivity 
{
	
	Button btn_find;
    GoogleMap mMap;
    EditText et_place;
	
	 @Override
	 protected void onCreate(Bundle savedInstanceState) 
	 {
		 	super.onCreate(savedInstanceState);
		 	setContentView(R.layout.geo1_layout);
		 	
		 	 // Getting reference to the SupportMapFragment
	        SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
	 
	        // Getting reference to the Google Map
	        mMap = mapFragment.getMap();
		 	
		 	f();
		 	
	        btn_find = (Button) findViewById(R.id.btn_find);
	        et_place = (EditText) findViewById(R.id.et_place);
		 	
	        /**********************************************/
	        // en cours
	        // http://wptrafficanalyzer.in/blog/locating-user-input-address-in-google-maps-android-api-v2-with-geocoding-api/
	        /**********************************************/

	        
	        btn_find.setOnClickListener(new OnClickListener() 
	        {
	 
		            @Override
		            public void onClick(View v) 
		            {
			                // Getting the place entered
			                String location = et_place.getText().toString();
			 
			                if(location==null || location.equals(""))
			                {
			                    Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
			                    return;
			                }
			 
			                String url = "https://maps.googleapis.com/maps/api/geocode/json?";
			 
			                try 
			                {
			                		// encoding special characters like space in the user input place
			                    	location = URLEncoder.encode(location, "utf-8");
			                } 
			                catch (UnsupportedEncodingException e) 
			                {
			                    e.printStackTrace();
			                }
			 
			                String address = "address=" + location;
			                String sensor = "sensor=false";
			 
			                // url , from where the geocoding data is fetched
			                url = url + address + "&" + sensor;
			 
			                // Instantiating DownloadTask to get places from Google Geocoding service
			                // in a non-ui thread
			                DownloadTask downloadTask = new DownloadTask();
			 
			                // Start downloading the geocoding places
			                downloadTask.execute(url);
		            }
	        });
	        
	        
	 
	 }
	 
	 
	 
	 /** A class, to download Places from Geocoding webservice */
	private class DownloadTask extends AsyncTask<String, Integer, String>
	{
	 
	        String data = null;
	 
	        // Invoked by execute() method of this object
	        @Override
	        protected String doInBackground(String... url) 
	        {
	            try{
	                	data = downloadUrl(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
	            ParserTask parserTask = new ParserTask();
	 
	            // Start parsing the places in JSON format
	            // Invokes the "doInBackground()" method of the class ParseTask
	            parserTask.execute(result);
	        }
	}
	 
	 
	 
	private String 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;
    } 
	
	 
	
	  /** A class to parse the Geocoding Places in non-ui thread */
    class ParserTask 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]);
 
                /** Getting the parsed data as a an ArrayList */
                places = parser.parse(jObject);
 
            }catch(Exception e){
                Log.d("Exception",e.toString());
            }
            return places;
        }
 
        // Executed after the complete execution of doInBackground() method
        @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
                mMap.addMarker(markerOptions);
 
                // Locate the first location
                if(i==0)
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        }
    }
	
	 
	 
	 public void f()
	 {
		 // http://www.techotopia.com/index.php/Working_with_the_Google_Maps_Android_API_in_Android_Studio
		 
		 // http://www.androidauthority.com/get-location-address-android-app-628764/
		 
		 double latitude = 0;
		 double longitude = 0;
		 
		 String Address1 = null;
		 String Address2;
		 String State;
		 String Zipcode;
		 String Country;

		 List<android.location.Address> geocodeMatches = null;

		 try 
		 {
		 	//geocodeMatches =  new Geocoder(this).getFromLocationName("600 Independence Ave SW, Washington, DC 20560", 1);
		 	//geocodeMatches =  new Geocoder(this).getFromLocation(38.8874245, -77.0200729, 1);
		 	
		 	geocodeMatches =  new Geocoder(this).getFromLocationName("201 6th Street Southwest Washington", 1);  // 
		 	//201 6th St SW
		 	//Washington, DC 20024 
		 	
	     } 
		 catch (IOException e) 
		 {
		 	// TODO Auto-generated catch block
		 	e.printStackTrace();
		 }

		 if (!geocodeMatches.isEmpty())
		 {
		 	latitude = geocodeMatches.get(0).getLatitude(); 
		 	longitude = geocodeMatches.get(0).getLongitude();
		 }
		 
		 
		 if (!geocodeMatches.isEmpty())
		 {
		 	Address1 = geocodeMatches.get(0).getAddressLine(0);
		 	Address2 = geocodeMatches.get(0).getAddressLine(1);
		 	State = geocodeMatches.get(0).getAdminArea();
		 	Zipcode = geocodeMatches.get(0).getPostalCode();
		 	Country = geocodeMatches.get(0).getCountryName();
		 }
		 
		 String str = Address1;
		 
	 }
	 
}



class GeocodeJSONParser {
	 
    /** Receives a JSONObject and returns a list */
    public List<HashMap<String,String>> parse(JSONObject jObject){
 
        JSONArray jPlaces = null;
        try {
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray("results");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
        * where each json object represent a place
        */
        return getPlaces(jPlaces);
    }
 
    private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
        int placesCount = jPlaces.length();
        List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> place = null;
 
        /** Taking each place, parses and adds to list object */
        for(int i=0; i<placesCount;i++){
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject)jPlaces.get(i));
                placesList.add(place);
 
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
 
        return placesList;
    }
 
    /** Parsing the Place JSON object */
    private HashMap<String, String> getPlace(JSONObject jPlace){
 
        HashMap<String, String> place = new HashMap<String, String>();
        String formatted_address = "-NA-";
        String lat="";
        String lng="";
 
        try {
            // Extracting formatted address, if available
            if(!jPlace.isNull("formatted_address")){
                formatted_address = jPlace.getString("formatted_address");
            }
 
            lat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
            lng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
 
            place.put("formatted_address", formatted_address);
            place.put("lat", lat);
            place.put("lng", lng);
 
        }catch (JSONException e) {
            e.printStackTrace();
        }
        return place;
    }
}