package com.example.GPS_DB02;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;

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.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/


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>();  
	
	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;
	
	Dialog dialog;
	EditText filename;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.control_service_layout);
		
		db = new DB_GPS(getApplicationContext());
	
		btn_start = (Button) findViewById(R.id.button1);    
		btn_stop = (Button) findViewById(R.id.button2);  
		btn_save = (Button) findViewById(R.id.button3);  
		btn_save.setEnabled(false); 
		
		enable_buttons();
		
	}

	
	@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 = Double.valueOf(gps_parameters[0]);  // + 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;
        			
        			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);
        }
    }
	
	
	private void enable_buttons()
	{
		btn_start.setOnClickListener(new OnClickListener() 
		{

				@Override
				public void onClick(View arg0) 
				{
					// enregistre le debut du run
					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_stop.setOnClickListener(new OnClickListener() 
		{

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

		});

		btn_save.setOnClickListener(new OnClickListener() 
		{

				@Override
				public void onClick(View arg0) 
				{
								Toast.makeText(getApplicationContext(), "Save...", Toast.LENGTH_LONG).show();
								save_dialog();
				}

		});

		
	}

	public void save_dialog()
	{
					final Dialog dialog = new Dialog(this);
					
					dialog.setContentView(R.layout.layout01);
					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 s = filename.getText().toString();
								save_DB(s);
								
		        				Toast.makeText(getApplicationContext(),"Traitement ...",Toast.LENGTH_SHORT).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); 
			
			
			db.save_infos_RUN(name, 100, run_start , run_start, 10000, "walk", 123.123, 8.74, distance , 555 ); 
		
	}
	
	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:"));
	*/	
	}
	
}

