package com.example.geo_api01;

import java.io.IOException;
import java.io.InputStream;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.TargetApi;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
 
//@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity 
{
    Button btn;
    TextView text;
    
    static double latitude;
    static double longitude;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btn = (Button) findViewById(R.id.btn);
        text = (TextView) findViewById(R.id.text);
 
        btn.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String addressText = getCurrentLocationViaJSON(43.7765, 2.1888);
                //String addressText = getCurrentLocationViaJSON(21.1271351, 79.1153546);
                
                text.setText(addressText);
                
                
             //   GeoPoint srcGeoPoint =getGeoPoint(getLocationInfo(fromAddress.replace("\n"," ").replace(" ", "%20")));
             //   GeoPoint destGeoPoint =getGeoPoint(getLocationInfo(CalDescription.toAddress.replace("\n"," ").replace(" ", "%20")));
                JSONObject jsonObj = getLocationInfo("albi");
                
                getLatLong(jsonObj); 
                
                
                String pipo = "plouf";	
                pipo = "km";
            }
        });
 
    }
 
    public static JSONObject getLocationInfo(double lat, double lng) 
    {
 
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
 
            StrictMode.setThreadPolicy(policy);
 
            HttpGet httpGet = new HttpGet(
                    "http://maps.googleapis.com/maps/api/geocode/json?latlng="
                            + lat + "," + lng + "&sensor=true");
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            StringBuilder stringBuilder = new StringBuilder();
 
            try {
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {
 
            } catch (IOException e) {
 
            }
 
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject = new JSONObject(stringBuilder.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return jsonObject;
        }
        return null;
    }
 
    public static String getCurrentLocationViaJSON(double lat, double lng) {
 
        JSONObject jsonObj = getLocationInfo(lat, lng);
        Log.i("JSON string =>", jsonObj.toString());
 
        String Address1 = "";
        String Address2 = "";
        String City = "";
        String State = "";
        String Country = "";
        String County = "";
        String PIN = "";
 
        String currentLocation = "";
 
        try {
            String status = jsonObj.getString("status").toString();
            Log.i("status", status);
 
            if (status.equalsIgnoreCase("OK")) {
                JSONArray Results = jsonObj.getJSONArray("results");
                JSONObject zero = Results.getJSONObject(0);
                JSONArray address_components = zero
                        .getJSONArray("address_components");
 
                for (int i = 0; i < address_components.length(); i++) {
                    JSONObject zero2 = address_components.getJSONObject(i);
                    String long_name = zero2.getString("long_name");
                    JSONArray mtypes = zero2.getJSONArray("types");
                    String Type = mtypes.getString(0);
 
                    if (Type.equalsIgnoreCase("street_number")) {
                        Address1 = long_name + " ";
                    } else if (Type.equalsIgnoreCase("route")) {
                        Address1 = Address1 + long_name;
                    } else if (Type.equalsIgnoreCase("sublocality")) {
                        Address2 = long_name;
                    } else if (Type.equalsIgnoreCase("locality")) {
                        // Address2 = Address2 + long_name + ", ";
                        City = long_name;
                    } else if (Type
                            .equalsIgnoreCase("administrative_area_level_2")) {
                        County = long_name;
                    } else if (Type
                            .equalsIgnoreCase("administrative_area_level_1")) {
                        State = long_name;
                    } else if (Type.equalsIgnoreCase("country")) {
                        Country = long_name;
                    } else if (Type.equalsIgnoreCase("postal_code")) {
                        PIN = long_name;
                    }
 
                }
 
                currentLocation = Address1 + "," + Address2 + "," + City + ","
                        + State + "," + Country + "," + PIN;
 
            }
        } catch (Exception e) {
 
        }
        return currentLocation;
 
    }
    
    
    /******************************************************/
    
    private static JSONObject getLocationInfo(String address)
    {

        StringBuilder stringBuilder = new StringBuilder();
        try 
        {

        	address = address.replaceAll(" ","%20");    

        	HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        	HttpClient client = new DefaultHttpClient();
        	HttpResponse response;
        	stringBuilder = new StringBuilder();

            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            
            while ((b = stream.read()) != -1) 
            {
                stringBuilder.append((char) b);
            }
            
        } 
        catch (ClientProtocolException e) 
        {
            Log.i("getLocationInfo ClientProtocolException", e.toString());
        } 
        catch (IOException e) 
        {
            Log.i("getLocationInfo IOException", e.toString());
        }


        JSONObject jsonObject = new JSONObject();
        try 
        {
            jsonObject = new JSONObject(stringBuilder.toString());
        } 
        catch (JSONException e) 
        {
            // TODO Auto-generated catch block
            Log.i("getLocationInfo JSONException", e.toString());
        }

        return jsonObject;
    }

    private static boolean getLatLong(JSONObject jsonObject) 
    {
        try 
        {
           longitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
           Log.i("Log1", longitude+"");
           latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
           
           Log.i("lat1", latitude+"");
        }
        
        catch (JSONException e) 
        {
            longitude=0;
            latitude = 0;
            Log.i("getLatLong", e.toString());
            return false;
        }

        return true;
    }
    
    
    /******************************************************************************/
    
    
    
    
 
}