package com.example.tracker01;

import java.text.DecimalFormat;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {

    Chronometer simpleChronometer;
    Button start, pause, resume, clear;
    TextView speedTextView, distanceTextView;
    
    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_km = 0.0;
   	static double distance_m = 0.0;
   	
   	static double d_km = 0.0;
   	double d_metre  = 0.0;   
   	double vitesse = 0.0;
   	double temps = 3.0;
   	
      
   	static Intent global_intent;

    private long lastPause;
    
    static boolean lock = false;
    
    private double currentSpeed = 0.0f;
    
    
    @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]);
        			
        			  currentSpeed = speed_actual * 3.6f;
        			  
        			
        			
        			if( lock == true)
        			{	
	        			// first location
        				if(indice == 0)
	        			{
	        				// distance en metres
	        				d_km =  CalculationDistance(lat_start, lon_start , lat_actual, lon_actual); 
	        				lat_previous = lat_actual;
	            			lon_previous = lon_actual;
	        				indice = indice + 1;
	        				Toast.makeText(getApplicationContext(), "First ", Toast.LENGTH_LONG).show();
	        			}
	        			else
	        			{
	        				// distance en metres
	        				d_km =  CalculationDistance(lat_previous, lon_previous , lat_actual, lon_actual); 
	        				lat_previous = lat_actual;
	            			lon_previous = lon_actual;
	            			indice = indice + 1;
	            			Toast.makeText(getApplicationContext(), "processing  ", Toast.LENGTH_LONG).show();
	            			//indice = 28800;
	        			}
	        			
        				//distance_km = distance_km + d_km; 
	        			
        				// v  = d / t
        				
        				d_metre = d_km * 1000;
        				distance_m = distance_m + d_metre; 
        				vitesse = d_metre / temps; 
        				
        				String affiche_distance = "";
        				double km_format = 0.0;
        				
        				if(distance_m >= 1000)
        				{
        					km_format = distance_m / 1000; 
        					affiche_distance = String.valueOf(km_format) + " métres";
        				}
        				else
        				{
        					affiche_distance = String.valueOf(km_format) + " Km";
        				}
	        			
        				String affiche_vitesse = new DecimalFormat("#.##").format(vitesse) + " m/s";
	        			
        				speedTextView.setText(affiche_vitesse);
	        			distanceTextView.setText(affiche_distance);
	        			
        			}
/*        			
        			if(indice == 5)
        			{
        	               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.layout01);
      
        simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer);
        start = (Button) findViewById(R.id.btn_start);
        pause = (Button) findViewById(R.id.btn_pause);
        resume = (Button) findViewById(R.id.btn_resume);
        clear = (Button) findViewById(R.id.btn_stop);
        speedTextView = (TextView) findViewById(R.id.speedTextView);
        distanceTextView = (TextView) findViewById(R.id.distanceTextView);
        
        start.setEnabled(true);
        pause.setEnabled(false);
        resume.setEnabled(false);
        clear.setEnabled(false);
        
        //simpleChronometer.setFormat("HH:MM:SS");
        
        //formatChronometerText(simpleChronometer);
       //simpleChronometer.setText("00:00:00");
        
        ///android:format = "Timer: %s "
        
        simpleChronometer.setFormat("0%s");
        simpleChronometer.setFormat("00:%s");
        
        double a = 43.774276;
        double b = 2.188391;
        double c = 43.773845;
        double d = 2.187766;
        
        d = CalculationDistance(a, b, c, d);  
        double d_metre = d * 1000;
        
        // pour avoir des km / h on multiplie par 3.6
        // pour des m/s   on divise par 3.6
        
        // 90 km/h = 25 m/s
        
        String plouf = "jjj";
        
        start.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                simpleChronometer.setBase(SystemClock.elapsedRealtime());
                simpleChronometer.start();
                start.setEnabled(false);
                pause.setEnabled(true);
                resume.setEnabled(false);
                clear.setEnabled(true);
                
                
                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();
            	
            	Intent intent = new Intent(getApplicationContext(),GPS_Service.class);
                startService(intent);
                
                global_intent = intent;
                
                lock = true;
                
            }
        });
        
        pause.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
            	lastPause = SystemClock.elapsedRealtime();
           	    simpleChronometer.stop();
           	    start.setEnabled(false);
           	    pause.setEnabled(false);
           	    resume.setEnabled(true);
           	    clear.setEnabled(true);
                lock = false;

            }
        });
        
        resume.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
            	simpleChronometer.setBase(simpleChronometer.getBase() + SystemClock.elapsedRealtime() - lastPause);
            	simpleChronometer.start();
            	start.setEnabled(false);
            	pause.setEnabled(true);
           	    resume.setEnabled(false);
            	clear.setEnabled(true);
                lock = true;

            }
        });
        
        clear.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
            	simpleChronometer.setBase(SystemClock.elapsedRealtime());
            	simpleChronometer.stop();
            	start.setEnabled(true);
                pause.setEnabled(false);
                resume.setEnabled(false);
                clear.setEnabled(false);
                
                Intent intent = new Intent(getApplicationContext(),GPS_Service.class);
                stopService(intent);
                lock = false;

            }
        });

        
    }
    
   
    
    
    // 43.774276, 2.188391
    //43.773845, 2.187766
    
    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;
     }
    
    

    
}

