package com.example.Maps013;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class Geolocalisation02 extends Activity 
{
	
	protected static final String TAG = "***********" ;
	LocationManager locationManager;
	TextView tv_infos;
	TextView tv_latitude, tv_longitude, tv_altitude, tv_adresse, tv_ville, tv_pays, tv_date, tv_temps, tv_source;
	static String adresse = "";
	static String ville = "";
	static String pays = "";
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.geolocation_layout);
        
        tv_latitude = (TextView) findViewById(R.id.tv_latitude);
		tv_longitude = (TextView) findViewById(R.id.tv_longitude);
		tv_altitude = (TextView) findViewById(R.id.tv_altitude);
		tv_adresse = (TextView) findViewById(R.id.tv_adresse);
		tv_ville = (TextView) findViewById(R.id.tv_ville);
		tv_pays = (TextView) findViewById(R.id.tv_pays);
		tv_date = (TextView) findViewById(R.id.tv_date);
		tv_temps = (TextView) findViewById(R.id.tv_temps);
		tv_source = (TextView) findViewById(R.id.tv_source);
		tv_infos = (TextView)findViewById(R.id.tv_infos);
        
		
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(lastLocation != null)
        {
        	updateLoc(lastLocation);
        }
    }
    
    private class GeoCoderHandler extends Handler 
    {
        @Override
        public void handleMessage(Message message) 
        {
            String result;
            switch (message.what) 
            {
                case 1:
                    Bundle bundle = message.getData();
                    result = bundle.getString("address");
                    break;
                default:
                    result = null;
            }
            //tv_altitude.setText(result);
        }
    }
    
    public static void getAddressFromLocation(final Location location, final Context context, final Handler handler) 
    {
        Thread thread = new Thread() 
        {
            @Override public void run()
            {
	                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
	                String result = null;
	                try 
	                {
	                    List<Address> list = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
	                    if (list != null && list.size() > 0)
	                    {
	                    		Address address = list.get(0);
	                    		result = address.getAddressLine(0) + ", " + address.getLocality() + ", " +  address.getCountryName() ;
	                    		
	                    		adresse = address.getAddressLine(0); 
	                    		ville = address.getLocality(); 
	                    		pays = address.getCountryName(); ;
	                    		
	                    }
	                } 
                
	                catch (IOException e) 
	                {
                    Log.e(TAG, "Impossible to connect to Geocoder", e);
	                } 
	                
	                finally 
	                {
	                	Message msg = Message.obtain();
	                	msg.setTarget(handler);
	                	if (result != null) 
	                	{
	                		msg.what = 1;
	                		Bundle bundle = new Bundle();
	                		bundle.putString("address", result);
	                		msg.setData(bundle);
	                	} 
	                	else
                        msg.what = 0;
	                	
	                	msg.sendToTarget();
	                }
            }
        };
        thread.start();
    }
    
    
    private void updateLoc(Location loc)
    {
    	
    	String locLog = "";
    	
    	getAddressFromLocation(loc, getApplicationContext(), new GeoCoderHandler());
    	
    			
		String formatedTime = (new SimpleDateFormat("EEE dd MMM yyyy | hh:mm:ss")).format(loc.getTime());
		
		double latitude = loc.getLatitude();
		double longitude = loc.getLongitude();
		double altitude = loc.getAltitude();
		
		tv_latitude.setText( Double.toString(latitude) );
		tv_longitude.setText( Double.toString(longitude) );
		tv_altitude.setText( Double.toString(altitude) );
		
		tv_adresse.setText( adresse );
		tv_ville.setText( ville );
		tv_pays.setText( pays );
		
		
		String date = (new SimpleDateFormat("EEE dd MMM yyyy")).format(loc.getTime());
		String temps = (new SimpleDateFormat("hh:mm:ss")).format(loc.getTime()) + "     " + String.valueOf(loc.getTime());
		
		tv_date.setText(date  );
		tv_temps.setText(temps);
		
		tv_source.setText(loc.getProvider());
		
		
	    			
		locLog += 
	    					 "@ " + formatedTime + "\n"
	    					+ "Latitude: " + loc.getLatitude() + " (°)\n"
	    					+ "Longitude: " + loc.getLongitude() + " (°)\n"
	    					+ "Time: " +  String.valueOf(loc.getTime()) + "\n"
	    					+ "Provider: " + loc.getProvider() + "\n";
	    			
	    if(loc.hasAltitude())
	    {
	    	locLog += "Altitude: " + loc.getAltitude() + " (m)\n";
	    }
	    			
	    if(loc.hasAccuracy())
	    {
	    	locLog += "Accuracy: " + loc.getAccuracy() + " (m)\n";
	    }
	    			
	    if(loc.hasBearing())
	    {
	    	locLog += "Bearing: " + loc.getBearing() + " (m)\n";
	    }
	    			
	    if(loc.hasSpeed())
	    {
	    	locLog += "Speed: " + loc.getSpeed() + " (m)\n";
	    }

    	//tv_infos.setText(locLog);
    }
    
	@Override
	protected void onResume() 
	{
		// TODO Auto-generated method stub
		super.onResume();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, myLocationListener);
	}
    
    @Override
	protected void onPause() 
    {
		// TODO Auto-generated method stub
		super.onPause();
		locationManager.removeUpdates(myLocationListener);
	}

    private LocationListener myLocationListener = new LocationListener()
    {

		@Override
		public void onLocationChanged(Location location) 
		{
			updateLoc(location);
			
		}

		@Override
		public void onProviderDisabled(String provider) 
		{
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) 
		{
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras)
		{
			// TODO Auto-generated method stub
			
		}
		
	};
		
}