package com.example.tracker02;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
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.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

// https://play.google.com/store/apps/details?id=com.dungelin.pedometer

public class MainActivity extends Activity 
{

    Chronometer simpleChronometer;
    Button start, pause, resume, clear;
    TextView speedTextView, distanceTextView;
    
    private BroadcastReceiver broadcastReceiver;
    
    
	private TextView tv_timer;
	private TextView tv_distance;
	private TextView tv_calories;
	private TextView tv_clock;
	private TextView tv_velocity;
	private TextView tv_step;
	
	private TextView tv_latitude;
	private TextView tv_longitude;
	private TextView tv_altitude;

	
	private Button btn_start;
	private Button btn_pause;
	private Button btn_resume;
	private Button btn_stop;
	
    private TextView tv_gps;
   
    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;
    
    private long timer = 0;
	private  long startTimer = 0;
	private  long tempTime = 0;

	private Double distance = 0.0;
	private Double calories = 0.0;
	private Double velocity = 0.0;

	private int step_length = 0;  
	private int weight = 0;       
	private int total_step = 0;   

	private Thread thread;  

	
	boolean stop_tag = false;
	
    
    
    /******************************************************************/
    
    Handler handler = new Handler() 
	{
		
		@Override               
		public void handleMessage(Message msg) 
		{
			super.handleMessage(msg);      

			countDistance();    
			countStep();      
		
			if (timer != 0 && distance != 0.0) 
			{
				calories = weight * distance * 0.001;
				velocity = distance * 1000 / timer;
			} 
			else 
			{
				calories = 0.0;
				velocity = 0.0;
			}

			   

			//tv_timer.setText(getFormatTime(timer));
			//tv_distance.setText(formatDouble(distance));
			//tv_calories.setText(formatDouble(calories));
			//tv_velocity.setText(formatDouble(velocity));
			tv_step.setText(total_step + "");
			
			 if(broadcastReceiver == null)
			 {
		            broadcastReceiver = new BroadcastReceiver() 
		            {
		                @Override
		                public void onReceive(Context context, Intent intent) 
		                {

		                	String str = (String) intent.getExtras().get("coordinates");
		                	String[] gps_parameters =  str.split(" ");
		                	//tv_gps.setText("" + intent.getExtras().get("coordinates"));	
		                }
		            };
		     }
		     
			 registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
			 
		
		}

	};
    
    
    /******************************************************************/
    
    @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( 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_speed_gps = String.valueOf(speed_actual) + " m/s";
        				
        				String affiche_vitesse = new DecimalFormat("#.##").format(vitesse) + " m/s";
        				String affiche_altitude = new DecimalFormat("#.##").format(alt_actuel) + " m";	

        				String affiche_latitude = new DecimalFormat("#.######").format(lat_actual);	
        				String affiche_longitude = new DecimalFormat("#.####").format(lon_actual);	

        				
	        			tv_distance.setText(affiche_distance);
        				tv_velocity.setText(affiche_vitesse);

        				tv_latitude.setText(affiche_latitude);	
        				tv_longitude.setText(affiche_longitude);	

        				
        				tv_gps.setText(affiche_speed_gps);	
        				tv_altitude.setText(affiche_altitude);	
        				
        				
        				
                    	//tv_altitude.setText("" + intent.getExtras().get("coordinates"));	
	        			
        			}
/*        			
        			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);
        setContentView(R.layout.tracker_view);
        
        simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer);
        simpleChronometer.setFormat("0%s");
        simpleChronometer.setFormat("00:%s");
        
        //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);
        

		//tv_timer = (TextView) this.findViewById(R.id.tv_timer);
		tv_distance = (TextView) this.findViewById(R.id.tv_distance);
		tv_calories = (TextView) this.findViewById(R.id.tv_calories);
		tv_clock = (TextView) this.findViewById(R.id.tv_clock);
		tv_velocity = (TextView) this.findViewById(R.id.tv_velocity);
		tv_step = (TextView)findViewById(R.id.tv_step);
		tv_gps = (TextView) findViewById(R.id.tv_gps);   
		
		tv_latitude = (TextView) findViewById(R.id.tv_latitude);   
		tv_longitude = (TextView) findViewById(R.id.tv_longitude);   
		tv_altitude = (TextView) findViewById(R.id.tv_altitude);   
		
		btn_start = (Button) this.findViewById(R.id.btn_start);
		btn_pause = (Button) this.findViewById(R.id.btn_pause);
		btn_resume = (Button) this.findViewById(R.id.btn_resume);
		btn_stop = (Button) this.findViewById(R.id.btn_stop);
		
		btn_start.setEnabled(true);
	    btn_pause.setEnabled(false);
	    btn_resume.setEnabled(false);
	    btn_stop.setEnabled(false);
		
	    Intent service = new Intent(this, StepCounterService.class);
		stopService(service);
		
		StepDetector.CURRENT_SETP = 0;
		tempTime = timer = 0;
		
		
		tv_step.setText("0");
		handler.removeCallbacks(thread);
		
        
		//btn_start.setEnabled(!StepCounterService.FLAG);
		//btn_stop.setEnabled(StepCounterService.FLAG);
		
	    
	    if (thread == null)
		{

			thread = new Thread() 
			{
				
					@Override
					public void run()
					{
						super.run();
						int temp = 0;
						while (true) 
						{
								try 
								{
									Thread.sleep(300); // 300
								} 
								catch (InterruptedException e) 
								{
									e.printStackTrace();
								}
								
								if (StepCounterService.FLAG) 
								{
									Message msg = new Message();
									if (temp != StepDetector.CURRENT_SETP) 
									{
										temp = StepDetector.CURRENT_SETP;
									}
									
									if (startTimer != System.currentTimeMillis()) 
									{
										timer = tempTime + System.currentTimeMillis() - startTimer;
									}
									handler.sendMessage(msg);
								}
						}
					}
			};
			
			thread.start();
		}
		
		/************* pour la clock ********************/
	    
		Thread t = new Thread() 
		{

		        @Override
		        public void run() 
		        {
		            try 
		            {
		                while (!isInterrupted())
		                {
		                    Thread.sleep(1000);
		                    runOnUiThread(new Runnable() 
		                    {
			                        @Override
			                        public void run()
			                        {
			                            updateClock();
			                        }
		                    });
		                }
		            } 
		            catch (InterruptedException e) 
		            {
		            }
		        }
		    };

	    t.start();
		
	    /************************************************/
	    
     
        
        btn_start.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                simpleChronometer.setBase(SystemClock.elapsedRealtime());
                simpleChronometer.start();
                btn_start.setEnabled(false);
                btn_pause.setEnabled(true);
                btn_resume.setEnabled(false);
                btn_stop.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;
                
            }
        });
        
        btn_pause.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
            	lastPause = SystemClock.elapsedRealtime();
           	    simpleChronometer.stop();
           	    btn_start.setEnabled(false);
           	    btn_pause.setEnabled(false);
           	    btn_resume.setEnabled(true);
           	 	btn_stop.setEnabled(true);
                lock = false;

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

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

            }
        });

        
    }
    
/*    
    public void onClick(View view) 
	{
    	 Intent intent;
		
		switch (view.getId())
		{
			case R.id.btn_start:
				
				simpleChronometer.setBase(SystemClock.elapsedRealtime());
                simpleChronometer.start();
				btn_start.setEnabled(false);
                btn_pause.setEnabled(true);
	            btn_resume.setEnabled(false);
	            btn_stop.setEnabled(true);
				
				//btn_stop.setText(getString(R.string.pause));
                
                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 = new Intent(getApplicationContext(),GPS_Service.class);
                startService(intent);
                
                global_intent = intent;
                
                lock = true;
	            
				
				break;
				
			case R.id.btn_pause:
				
				lastPause = SystemClock.elapsedRealtime();
           	    simpleChronometer.stop();
           	    btn_start.setEnabled(false);
           	    btn_pause.setEnabled(false);
           	    btn_resume.setEnabled(true);
           	    btn_stop.setEnabled(true);
                lock = false;
				
				break;	
				
			case R.id.btn_resume:

            	simpleChronometer.setBase(simpleChronometer.getBase() + SystemClock.elapsedRealtime() - lastPause);
            	simpleChronometer.start();
            	btn_start.setEnabled(false);
            	btn_pause.setEnabled(true);
           	    btn_resume.setEnabled(false);
            	btn_stop.setEnabled(true);
                lock = true;
				
				break;	
				
			case R.id.btn_stop:
				
				simpleChronometer.setBase(SystemClock.elapsedRealtime());
            	simpleChronometer.stop();
            	btn_start.setEnabled(true);
                btn_pause.setEnabled(false);
                btn_resume.setEnabled(false);
                btn_stop.setEnabled(false);
                lock = false;

                intent = new Intent(getApplicationContext(),GPS_Service.class);
                stopService(intent);
             
                
				break;	
		}
	}
*/
   
    private void updateClock() 
	{
	    Date clock = Calendar.getInstance().getTime();

	    String time = "hh:mm:ss"; // 12:00
	    tv_clock.setText(DateFormat.format(time, clock));

	 
	}
    
    // 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;
     }
    
    
    public void about()
	{
		
		//http://androidexample.com/Custom_Dialog_-_Android_Example/index.php?view=article_discription&aid=88
		
        final Dialog dialog = new Dialog(MainActivity.this);
        dialog.setContentView(R.layout.about_layout);
        dialog.setTitle("About:");
        dialog.show();
        
        
        Button dialogCloseButton = (Button) dialog.findViewById(R.id.close_button);
        dialogCloseButton.setOnClickListener(new OnClickListener()
        {
              @Override
              public void onClick(View v)
              {
               // TODO Auto-generated method stub
                  dialog.dismiss();
              }                                                                             
         });
		
	} 
    
    /*******************************************************************************************/
    
    private void countDistance()
	{
		if (StepDetector.CURRENT_SETP % 2 == 0)
		{
			distance = (StepDetector.CURRENT_SETP / 2) * 3 * step_length * 0.01;
		} 
		else 
		{
			distance = ((StepDetector.CURRENT_SETP / 2) * 3 + 1) * step_length * 0.01;
		}
	}


	private void countStep() 
	{
		if (StepDetector.CURRENT_SETP % 2 == 0) 
		{
			total_step = StepDetector.CURRENT_SETP;
		} 
		else
		{
			total_step = StepDetector.CURRENT_SETP +1;
		}

		total_step = StepDetector.CURRENT_SETP;
	}
    
    @Override
	public void onBackPressed()
	{
		
					AlertDialog.Builder dialog = new AlertDialog.Builder(this)
				    .setTitle("Warning !")
				    .setCancelable(false)
				    .setMessage("Do you really want to close podometre?")
				    .setIcon(R.drawable.ic_launcher)
				    
				    .setNegativeButton("No", new DialogInterface.OnClickListener()
				    //.setNegativeButton("No", new OnClickListener()
				    {
					    	public void onClick(DialogInterface dialog, int which)
					    	{
					    		dialog.dismiss();
					    	}
				    })
				    
				    //.setPositiveButton("Yes", new OnClickListener() 
				  	.setPositiveButton("Yes", new DialogInterface.OnClickListener()
				    {
						   public void onClick(DialogInterface dialog, int which)
						   {
							   MainActivity.this.finish();
							   dialog.dismiss();
						   }
				    });
					
				  dialog.show();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
			getMenuInflater().inflate(R.menu.tracker02_menu, menu);
			return true;
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) 
	{
		
			Intent Intent;
		 
	        switch (item.getItemId())
	        {
	        
	        	case R.id.menu_settings:
	        		//Intent = new Intent(MainActivity.this, SettingsActivity.class);
	        		//startActivity(Intent);
	        		return true;
	        
	        	case R.id.menu_save:
	        		//Intent = new Intent(StepCounterActivity.this, test_DB.class); // SaveActivity
	        		//startActivity(Intent);
	        		return true;
	        		
	        	case R.id.menu_about:
	        		 about();
	        		return true;
	        		
	        		
		  		default:
		          return super.onOptionsItemSelected(item);
             }
    }
	
	/*******************************************************************************************/

    
}

