package com.example.GPS_DB01;

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

public class Control_Service extends Activity 
{
	
	Button btn_start, btn_stop, btn_save;
	TextView infos;
	private BroadcastReceiver broadcastReceiver;
	 
	DAOtextReport daOtextReport;
	 
	ArrayList<double[]> objPositions = new ArrayList<double[]>();
	  
	static  ArrayList<TextReport> objets= new ArrayList<TextReport>();  
	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);
		
		daOtextReport = new DAOtextReport(this);
		
		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); 
		
		infos = (TextView) findViewById(R.id.textView2);   
		
		enable_buttons();
		
		//daOtextReport.add_run(); 
	}

	
	@Override
    protected void onResume() 
	{
        super.onResume();
        if(broadcastReceiver == null)
        {
            broadcastReceiver = new BroadcastReceiver() 
            {
                @Override
                public void onReceive(Context context, Intent intent) 
                {

                    //infos.append("\n" +intent.getExtras().get("coordinates"));
                    Random_generator msr = new Random_generator();
            		
        			String report = msr.generateRandomString();
        			
        			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 speed = Double.valueOf(gps_parameters[3]);
        			
        			cpt = cpt + 1;
        			
        		//	long result = daOtextReport.addReport(new TextReport("patoche.com", report, lat , lng, alt, speed));
        			
        			TextReport id = new TextReport("not_defined", report, lat , lng, alt, speed);
        			objets.add(id);
        			
        			int n = objets.size();
        			if(n == 5)
        			{
        				String str = "stop";
        				str = str + " zorro ";
        				Toast.makeText(getApplicationContext(),"Stop le train ...",Toast.LENGTH_SHORT).show();
        			}
        			
                	//long result = daOtextReport.addReport(new TextReport("junjunguo.com", report, 63.4187362, 10.4387621, 1234, 90));


                }
            };
        }
        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();
								//pressed();
								bis();
				}

		});

		
	}
	
	
	// https://inducesmile.com/android-game-development/custom-dialog-and-custom-alertdialog-box-in-android/
	
	public void pressed()
	{
		
		dialog = new Dialog(this);
        dialog.setTitle("Address:");
        dialog.setContentView(R.layout.save_dialog_layout);

//        filename = (EditText)dialog.findViewById(R.id.filename);
  //      et_destination = (EditText)dialog.findViewById(R.id.et_address_destination);
  //      btn_find = (Button)dialog.findViewById(R.id.btn_find);
  //      btn_cancel = (Button)dialog.findViewById(R.id.btn_cancel);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Sample Alert");
        builder.setMessage("Two Action Buttons Alert Dialog");
        builder.setNegativeButton("NO",  new DialogInterface.OnClickListener() 
        {
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        Toast.makeText(getApplicationContext(),"No is clicked",Toast.LENGTH_LONG).show();
                    }
        });
        
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener()
        {
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
                    }
                });
        
        builder.show();
		
		
	}


	public void bis()
	{
					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;
			
		    // dans la table summary
			for(int i=0;i<n;i++)
			{
				    TextReport id =  Control_Service.objets.get(i);
				    id.setRunid(name);
					long result = daOtextReport.addReport(id);
			}
			
			// 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 pipo = Double.valueOf(arround);
			
			//run_start
			//run_stop
			//System.currentTimeMillis()
			
		
			
			daOtextReport.add_run(name, 100, run_start , run_start, 10000, "walk", 123.123, 8.74, distance , 555 ); 

			
			//daOtextReport.add_run(String name, long date, long start , long stop, long steps, String mode, long calories, long vitesse_moyenne, long distance, long duration ) 

			
			//daOtextReport.add_run(); 
		
		//long result = daOtextReport.addReport(new TextReport("junjunguo.com", report, 63.4187362, 10.4387621, 1234, 90));
		
	}
	
}

