package com.example.Maps013;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.ActionBar;
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.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import android.content.DialogInterface; 

//https://www.youtube.com/watch?v=lvcGh2ZgHeA
// Filip Vujovic 

// https://www.youtube.com/watch?v=QNb_3QKSmMk


// https://inducesmile.com/android-game-development/custom-dialog-and-custom-alertdialog-box-in-android/


//https://stackoverflow.com/questions/38237947/chronometer-with-hmmss

public class Control_Service extends Activity 
{
	
	Button btn_start, btn_stop, btn_save;
	TextView infos;
	private BroadcastReceiver broadcastReceiver;
	 
	
	DB_GPS db;
	private SQLiteDatabase dataBase;

	final static ArrayList<GPS> GPS = new ArrayList<GPS>();
	static  ArrayList<GPS> objets= new ArrayList<GPS>();  
	
	 ArrayList<RUN> ListRUN = new ArrayList<RUN>();
	
	int cpt = 0;
	double[] coef = {0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08};
		
	long run_start = 0;
	long run_stop = 0;
	Double coeff = 0.017;
	
	Dialog dialog;
	EditText filename;
	
	boolean device_emulator;
	
	TextView message;
	TextView tv_timer;
	
	Chronometer chrono;
	
	long timer = 0;
	
	Timer T=new Timer();
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.control_service_layout);
		
		db = new DB_GPS(getApplicationContext());
		
		ActionBar actionBar = getActionBar();
        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("GPS Tracker");
	
		btn_start = (Button) findViewById(R.id.button1);    
		btn_stop = (Button) findViewById(R.id.button2);  
		btn_save = (Button) findViewById(R.id.button3);  
		
		tv_timer = (TextView) this.findViewById(R.id.tv_timer);
		
		btn_start.setEnabled(true); 
		btn_stop.setEnabled(false); 
		btn_save.setEnabled(false); 
		
		enable_buttons();
		
		if (Build.BRAND.equalsIgnoreCase("generic"))
		{
			device_emulator = true; 
            //Toast.makeText(getBaseContext(), "YES, I am an emulator", Toast.LENGTH_LONG).show();
		} 
		else 
		{
			device_emulator = false;	
          //Toast.makeText(getBaseContext(), "NO, I am NOT an emulator", Toast.LENGTH_LONG).show();
        }
		

		 //chrono = (Chronometer) findViewById(R.id.chronometer);
		
	}

	
	@Override
    protected void onResume() 
	{
        super.onResume();
        if(broadcastReceiver == null)
        {
            broadcastReceiver = new BroadcastReceiver() 
            {
                @Override
                public void onReceive(Context context, Intent intent) 
                {
        			String s = (String) intent.getExtras().get("coordinates");
        			String[] gps_parameters = s.split(" "); 
        			
        			Double lat = 0.0;
        			
        			if(device_emulator == true)
        			{
        				 lat = Double.valueOf(gps_parameters[0]) + coeff ;  // + coef[cpt]; 
        			}
        			else
        			{
        				lat = Double.valueOf(gps_parameters[0]); //+ coeff ;  // + coef[cpt]; 
        			}
        			//Double lat = Double.valueOf(gps_parameters[0]); //+ coeff ;  // + coef[cpt]; 
        			Double lng = Double.valueOf(gps_parameters[1]); // + cpt;
        			Double alt = Double.valueOf(gps_parameters[2]);
        			Double vitesse = Double.valueOf(gps_parameters[3]);
        			
        			cpt = cpt + 1;
        			coeff = coeff + 0.01;
        			
        			long now = System.currentTimeMillis();
        			GPS infos = new GPS("no_name", now  , lat, lng , alt, vitesse);
        			objets.add(infos);
        			//long ret = db.save_infos_GPS(infos); 
        			
        			int n = Control_Service.objets.size();
        			if(n == 5)
        			{
        				Toast.makeText(getApplicationContext(),"Stop le train ...",Toast.LENGTH_SHORT).show();
        			}

                }
            };
        }
        registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
    }
	
	@Override
    protected void onDestroy() 
	{
        super.onDestroy();
        if(broadcastReceiver != null)
        {
            unregisterReceiver(broadcastReceiver);
        }
    }
	
/*	
	// creating timer task, timer
	   TimerTask tasknew = new TimerScheduleFixedRate();
	   Timer timer = new Timer();
	      
	   // scheduling the task at fixed rate
	   timer.scheduleAtFixedRate(tasknew,new Date(),1000);      
	   }
	   // this method performs the task
	   public void run() {
	   System.out.println("working at fixed rate");      
	   }    
*/	
	
	private void enable_buttons()
	{
		btn_start.setOnClickListener(new OnClickListener() 
		{
			
				
				@Override
				public void onClick(View arg0) 
				{
					// enregistre le debut du run
					//chrono.start();
					//chrono.setFormat("Time (%s)");
					//chrono.setFormat("H:MM:SS");
					
					T.scheduleAtFixedRate(new TimerTask() 
					{         
					        @Override
					        public void run() {
					            runOnUiThread(new Runnable()
					            {
					                @Override
					                public void run()
					                {
					                	//tv_timer.setText("count="+count);
					            		String pif = getFormatTime(timer);
					                	
					                	//SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
					                	//String time = df.format(timer);
					                	
					            		tv_timer.setText(pif);
					            		
					            		Toast.makeText(getApplicationContext(),"Stop le train ...",Toast.LENGTH_SHORT).show();
					                    timer++;                
					                    
					                    String strLong = Long.toString(timer);
					                    Log.v("blah", strLong);
					                    
					                }
					            });
					        }
					}, 1000, 1000);
					
					
					run_start = System.currentTimeMillis();
					Intent i = new Intent(getApplicationContext(), GPS_Service.class);
					startService(i);
					Toast.makeText(getApplicationContext(), "Start GPS service", Toast.LENGTH_LONG).show();
					btn_start.setEnabled(false); 
					btn_stop.setEnabled(true); 
					btn_save.setEnabled(false); 
				}

		});
		
		btn_stop.setOnClickListener(new OnClickListener() 
		{

				@Override
				public void onClick(View arg0) 
				{
					// enregistre la fin du run
					//chrono.stop();
					run_stop = System.currentTimeMillis();
					btn_start.setEnabled(false); 
					btn_stop.setEnabled(false); 
					btn_save.setEnabled(true); 
					Intent i = new Intent(getApplicationContext(), GPS_Service.class);
					stopService(i);
					Toast.makeText(getApplicationContext(), "Stop service : down", Toast.LENGTH_LONG).show();
					T.cancel();
					T.purge();
					T = null;
					
					
					
				}

		});

		btn_save.setOnClickListener(new OnClickListener() 
		{

				@Override
				public void onClick(View arg0) 
				{
								Toast.makeText(getApplicationContext(), "Save...", Toast.LENGTH_LONG).show();
								save_dialog();
								btn_start.setEnabled(true);
								btn_stop.setEnabled(false); 
								btn_save.setEnabled(false);
				}

		});

		
	}

	public void save_dialog()
	{
					final Dialog dialog = new Dialog(this);
					
					dialog.setContentView(R.layout.dialog_save_file);
					dialog.setTitle("Sauvegarde du run :");

					filename = (EditText) dialog.findViewById(R.id.filename);
					
					Button cancel = (Button) dialog.findViewById(R.id.btn_cancel);
					cancel.setOnClickListener(new OnClickListener()
					{
							@Override
							public void onClick(View v) 
							{
								dialog.dismiss();
							}
					});

					Button ok = (Button) dialog.findViewById(R.id.btn_ok);
					ok.setOnClickListener(new OnClickListener()
					{
							@Override
							public void onClick(View v)
							{
								String file = filename.getText().toString().toLowerCase();
								String concate = "";
								
								ListRUN  = db.RUNgetAllRecords();
								for(int i=0;i<ListRUN.size()-1;i++)
								{
									 concate = concate + " "  + ListRUN.get(i).nom;
								}		
								
								if(concate.contains(file))
								{
			        				Toast.makeText(getApplicationContext(),"RUN exist indatabase !.",Toast.LENGTH_LONG).show();
			        				message = (TextView) dialog.findViewById(R.id.tv_message);
			        				message.setText("File exist !");
			        				//dialog.dismiss();
								}
								else
								{	
									//save_DB(file);
									String str_msg = "Sauvegarde du RUN " + file;
									Toast.makeText(getApplicationContext(), str_msg ,Toast.LENGTH_LONG).show();
								    dialog.dismiss();
								}
							}
					});
					
					dialog.show();
					
				
	}
	
	
	public void save_DB(String name)
	{
		   
		 	int n = Control_Service.objets.size();
		    double distance = 0.0;
		
			for(int i=0;i<n;i++)
			{
				    GPS infos =  Control_Service.objets.get(i);
				    infos.setNom(name);
					long ret = db.save_infos_GPS(infos); 
			}
			
			// dans la table run
			for(int i=0;i<n-1;i++)
			{
				Double lat1 = Control_Service.objets.get(i).getLatitude();
				Double lng1 = Control_Service.objets.get(i).getLongitude();
				Double lat2 = Control_Service.objets.get(i+1).getLatitude();
				Double lng2 = Control_Service.objets.get(i+1).getLongitude();
				double d = Haversine.Haversine(lat1, lng1, lat2, lng2, "K"); 
				distance = distance + d; 
			}	

			DecimalFormat df = new DecimalFormat("#.###");
			df.setRoundingMode(RoundingMode.HALF_UP);
			String arround =  df.format(distance); 
			//Double mydouble = Double.parseDouble(arround);  ????????
			
			
			 String aString = "78";
			 Double aDouble = Double.parseDouble(aString);
			
			 aString = "78.54645";
			 aDouble = Double.parseDouble(aString);
			
			 long duration = run_stop - run_start;
			 
			
			long xxx = Long.valueOf(n);
			 
			db.save_infos_RUN(name, run_start, run_start , run_stop, xxx, "walk", 123.123, 8.74, distance , duration ); 
																	// 12345		// calories vitesse		
	}
	
	
	public String getFormatTime(long time) 
	{
		/*
		time = time / 1000;
		long second = time % 60;
		long minute = (time % 3600) / 60;
		long hour = time / 3600;

		
		// String strMillisecond = "" + (millisecond / 10);
		
		String strSecond = ("00" + second)
				.substring(("00" + second).length() - 2);
	
		String strMinute = ("00" + minute)
				.substring(("00" + minute).length() - 2);
	
		String strHour = ("00" + hour).substring(("00" + hour).length() - 2);

		return strHour + ":" + strMinute + ":" + strSecond;
		// + strMillisecond;
		*/
		long hr = time/3600;
		long rem = time%3600;
		long mn = rem/60;
		 long sec = rem%60;
		  String hrStr = (hr<10 ? "0" : "")+hr;
		  String mnStr = (mn<10 ? "0" : "")+mn;
		  String secStr = (sec<10 ? "0" : "")+sec; 
		
		  String aqw =  hrStr + ":" + mnStr + ":" + secStr;
		  return aqw;
	}
	
	
	public void send()
	{
		
		/*Intent i = new Intent(Intent.ACTION_SEND);
		i.putExtra(Intent.EXTRA_EMAIL, new String[] {"recipient@domain.com"});
		i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
		i.putExtra(Intent.EXTRA_TEXT, "Some message text");
		i.setType("application/octet-stream");
		i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(databaseFile));
		startActivity(Intent.createChooser(i, "Send e-mail"));*/
	/*	
		 Intent sendIntent = new Intent(Intent.ACTION_SEND); 
	        sendIntent.putExtra(Intent.EXTRA_SUBJECT, "subject line"); 
	        sendIntent.putExtra(Intent.EXTRA_TEXT,"Body of email"); 
	        Uri uri = Uri.fromFile(getDatabasePath("TEST_DB"));
	        //uri = file:///data/data/com.gmailspike/databases/TEST_DB
	        sendIntent.putExtra(Intent.EXTRA_STREAM, uri); 
	        sendIntent.setType("application/octet-stream");

	        startActivity(Intent.createChooser(sendIntent,"Email:"));
	*/	
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
			//getMenuInflater().inflate(R.menu.control_service_menu, menu);
			getMenuInflater().inflate(R.menu.gps_tracker_menu, menu);
			
			return true;
	}
	
	

	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) 
	{
		Intent Intent;
				
        switch (item.getItemId())
        {	
                
        	case android.R.id.home:
        		this.finish();
        		return true;
/*        
	  		case R.id.menu_list_run:
	  			Intent = new Intent(Control_Service.this, Listing_run.class);
	  			startActivity(Intent);
		        return true;       
*/		        

      		case R.id.listing_runs:
      			Toast.makeText(getApplicationContext(),"Listing runs",Toast.LENGTH_SHORT).show();
      			Intent = new Intent(Control_Service.this, Listing_run.class);
	  			startActivity(Intent);
      			return true;
	          
/*		        
	  		case R.id.menu_about:
	  			Toast.makeText(getApplicationContext(),"Not define",Toast.LENGTH_SHORT).show();
		        return true;
	
	  		case R.id.menu_quit:
	  			Toast.makeText(getApplicationContext(),"Salut on ferme la boutique...",Toast.LENGTH_SHORT).show();
	  			finish();
		        return true;    
*/	          
	  		default:
	          return super.onOptionsItemSelected(item);
        
        }
    }
	
	
	
	    
	
}

