package com.example.distance02;

import android.util.Log;
import java.text.DecimalFormat;

import com.google.android.gms.maps.model.LatLng;
import android.app.Activity;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

//http://andrew.hedges.name/experiments/haversine/

//https://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

//http://www.sanfoundry.com/java-android-program-start-stop-service/

//https://github.com/miskoajkula/GPS_service

//https://github.com/jmsong/haversine-distance/tree/master/app/src/main/java/com/coccoc/haversinedistance

public class MainActivity extends Activity 
{

    private Button btn_start, btn_stop;
    private TextView textView;
    private BroadcastReceiver broadcastReceiver;
    
    static double lat_start;
	static double lon_start;
	static double altitude_start; 
	static double speed_start; 
	static double time_start; 
	
	static int indice = 0;
	
	static double lat_previous = 0.0;
	static double lon_previous = 0.0;
	
	static double distance = 0.0;
	static double d = 0.0;
    
   
	static Intent global_intent;

    @Override
    protected void onResume() 
    {
        super.onResume();
        if(broadcastReceiver == null)
        {
            broadcastReceiver = new BroadcastReceiver() 
            {
                @Override
                public void onReceive(Context context, Intent intent)
                {
                    textView.append("\n" +intent.getExtras().get("coordinates"));
                    
                    String s = (String) intent.getExtras().get("coordinates");
        			String[] gps_parameters = s.split(" "); 
        			
        			double lat_actual = Double.valueOf(gps_parameters[0]); 
        			double lon_actual = Double.valueOf(gps_parameters[1]); 
        			double alt_actuel = Double.valueOf(gps_parameters[2]);
        			double speed_actual = Double.valueOf(gps_parameters[3]);
        			
        			if(indice == 0)
        			{
        				// distance en metres
        				d=  CalculationDistance(lat_start, lon_start , lat_actual, lon_actual); 
        				lat_previous = lat_actual;
            			lon_previous = lon_actual;
        				indice = indice + 1;
        			}
        			else
        			{
        				// distance en metres
        				d =  CalculationDistance(lat_previous, lon_previous , lat_actual, lon_actual); 
        				lat_previous = lat_actual;
            			lon_previous = lon_actual;
            			indice = indice + 1;
            			//indice = 28800;
        			}
        			
        			distance = distance + d; 
        			
        			if(indice == 5)
        			{
        				 //Intent intent = new Intent(getApplicationContext(),GPS_Service.class);
        	               stopService(global_intent);
        	                btn_start.setEnabled(true); 
        	        		btn_stop.setEnabled(false); 
                		
                		distance = 0.0;
                		indice = 0;
                		
                		Toast.makeText(getApplicationContext(), "Process stopped ! ", Toast.LENGTH_LONG).show();
        			}
        			
        			// 20 * 60 * 24
        			
        			
                    
                }
            };
        }
        registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
    }

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
        if(broadcastReceiver != null)
        {
            unregisterReceiver(broadcastReceiver);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_start = (Button) findViewById(R.id.button);
        btn_stop = (Button) findViewById(R.id.button2);
        textView = (TextView) findViewById(R.id.textView);

    	btn_start.setEnabled(true); 
		btn_stop.setEnabled(false); 
      
        enable_buttons();

    }

    private void enable_buttons() 
    {

        btn_start.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View view) 
            {
                
            	
            	LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            	Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            	
            	lat_start = location.getLatitude();
            	lon_start = location.getLongitude();
            	altitude_start = location.getAltitude();
            	speed_start = location.getSpeed();
            	time_start = location.getTime();
            	// bear
            	// accuracy
            	
            	//Intent i =new Intent(getApplicationContext(),GPS_Service.class);
            	Intent intent = new Intent(getApplicationContext(),GPS_Service.class);
                startService(intent);
                
                global_intent = intent;
            	
                btn_start.setEnabled(false); 
				btn_stop.setEnabled(true); 
				
				
				
            }
        });

        btn_stop.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View view) 
            {

                //Intent i = new Intent(getApplicationContext(),GPS_Service.class);
                Intent intent = new Intent(getApplicationContext(),GPS_Service.class);
                stopService(intent);
                btn_start.setEnabled(true); 
        		btn_stop.setEnabled(false); 
        		
        		distance = 0.0;
        		indice = 0;

            }
        });

    }
    
    public double CalculationDistance(double lat1, double lon1, double lat2, double lon2)  
    {
        int Radius=6371;//radius of earth in Km         
        double dLat = Math.toRadians(lat2-lat1);
        double dLon = Math.toRadians(lon2-lon1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult= Radius*c;
        double km=valueResult/1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec =  Integer.valueOf(newFormat.format(km));
        double meter=valueResult%1000;
        int  meterInDec= Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value",""+valueResult+"   KM  "+kmInDec+" Meter   "+meterInDec);

        return Radius * c;
     }

  
    
    
} 