package com.androidbegin.buttonclicktutorial;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;


import android.app.ActionBar.LayoutParams;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Space;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;


// http://www.java2s.com/Code/Java/Data-Type/Getdateofyesterday.htm


public class AddRepeat extends Activity //implements View.OnClickListener 
{

	private Button activeButton1 = null;
    private Button activeButton2 = null;
    private Button activeButton3 = null;
    private Button activeButton4 = null;
    private Button activeButton5 = null;
    private Button activeButton6 = null;
    private Button activeButton7 = null;
    
    String TAG_LUNDI = "";
    String TAG_MARDI = "";
    String TAG_MERCREDI = "";
    String TAG_JEUDI = "";
    String TAG_VENDREDI = "";
    String TAG_SAMEDI = "";
    String TAG_DIMANCHE = "";
    
    static int TAG_TITRE = 5250;
    static int TAG_TIME = 5251;

    
    Button button1 , button2, button3 , button4, button5 , button6 , button7;
    
	DB_alarm db;
	private SQLiteDatabase dataBase;
	
	String days_list_name = "";
	String days_list_num = "";


	int array_days_config_valeur[] = new int[7];
	String array_days_config_name[] = new String[7];
	
	//aPowersOfTwo[1]=Math.pow(2,1);
	
	final int TIME_DIALOG_ID = 0;
	private int mHour;
	private int mMinute;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.test06);
        
		db = new DB_alarm(getApplicationContext());
		
        ActionBar actionBar = getActionBar();
        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("Add repeat alarm");

    
		layout();
		
		button1 = (Button) findViewById(R.id.btn_day_lun);
		button2 = (Button) findViewById(R.id.btn_day_mar);
		button3 = (Button) findViewById(R.id.btn_day_mer);
		button4 = (Button) findViewById(R.id.btn_day_jeu);
		button5 = (Button) findViewById(R.id.btn_day_ven);
		button6 = (Button) findViewById(R.id.btn_day_sam);
		button7 = (Button) findViewById(R.id.btn_day_dim);
		
        initialisation();
        listner();

		
/*		
        Button btn_apply = (Button) findViewById(R.id.btn_apply);  
        btn_apply.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 						//sauver_configuration();
 						
 					 	String titre = "blabla";
 					 	long timestamp_start = 0;
 					 	String interval = "hour";
 					 	
 					 	long now = System.currentTimeMillis();
 					 	timestamp_start = now + (60 * 1000 * 5); // 5 sec
 						
 						long id = db.insert_repeat("titre1" ,  timestamp_start,  days_list_name , interval , "status", "option_vibrate", "option_ringtone" );
 					 	
						//Intent service = new Intent(config_alarm.this, AlarmService.class);
						//service.putExtra("ALARMID", id );   
						//service.putExtra("TIME", timestamp_start);
						//long interval_val = 20 * 1000; // 20 s 
						//service.putExtra("INTERVAL", interval_val);
						//service.setAction(AlarmService.REPEAT);
						//startService(service);  
						
						finish();
				        Toast.makeText(config_alarm.this,  "TRACE" , Toast.LENGTH_LONG).show();

 				}
 	    });
*/        
    }    
    
    /********************************************************************************/
	private void initialisation()
	{
		  Calendar calendar = Calendar.getInstance();
	      int current_day = calendar.get(Calendar.DAY_OF_WEEK);
	      
	      switch(current_day)
	    	{
	        	case 1:
	                	activeButton7 = button7; // dim
	                	button7.setSelected(true);
	                	break;
	        	case 2:
	                	activeButton1 = button1;  // lun
	                	button1.setSelected(true);
	                	break;
	        	case 3:
	                	activeButton2 = button2; // mar
	                	button2.setSelected(true);
	                	break;	
	        	case 4:
	                	activeButton3 = button3; // mer
	                	button3.setSelected(true);
	                	break;	
	        	case 5:
	                	activeButton4 = button4; // jeu
	                	button4.setSelected(true);
	                	break;
	        	case 6:
	                	activeButton5 = button5; // ven
	                	button5.setSelected(true);
	                	break;
	        	case 7:
	                	activeButton6 = button6; // sam
	                	button6.setSelected(true);
	                	break;	
	    	}
	      
	      
	}
	
    /********************************************************************************/
	private void listner()
	{
			 button1.setOnClickListener(new View.OnClickListener() 
			 {
				    @Override
				    public void onClick(View v)
				    {
				    	if (activeButton1 != null) 
		        		{
		                    button1.setSelected(false);
		                    activeButton1 = null;
		                }
		                else
		                {	
		                	activeButton1 = button1;
		                	button1.setSelected(true);
		                }
				    }
			 });
			 
			 button2.setOnClickListener(new View.OnClickListener() 
			 {
				    @Override
				    public void onClick(View v)
				    {
				    	if (activeButton2 != null) 
		        		{
		                    button2.setSelected(false);
		                    activeButton2 = null;
		                }
		                else
		                {	
		                	activeButton2 = button2;
		                	button2.setSelected(true);
		                }
				    }
			 });
		 		 
			 button3.setOnClickListener(new View.OnClickListener() 
			 {
				    @Override
				    public void onClick(View v)
				    {
				    	if (activeButton3 != null) 
		        		{
		                    button3.setSelected(false);
		                    activeButton3 = null;
		                }
		                else
		                {	
		                	activeButton3 = button3;
		                	button3.setSelected(true);
		                }
				    }
			 });
			 
			 button4.setOnClickListener(new View.OnClickListener() 
			 {
				    @Override
				    public void onClick(View v)
				    {
				    	if (activeButton4 != null) 
		        		{
		                    button4.setSelected(false);
		                    activeButton4 = null;
		                }
		                else
		                {	
		                	activeButton4 = button4;
		                	button4.setSelected(true);
		                }
				    }
			 });
			 
			 button5.setOnClickListener(new View.OnClickListener() 
			 {
				    @Override
				    public void onClick(View v)
				    {
				    	if (activeButton5 != null) 
		        		{
		                    button5.setSelected(false);
		                    activeButton5 = null;
		                }
		                else
		                {	
		                	activeButton5 = button5;
		                	button5.setSelected(true);
		                }
				    }
			 });
			 
			 button6.setOnClickListener(new View.OnClickListener() 
			 {
				    @Override
				    public void onClick(View v)
				    {
				    	if (activeButton6 != null) 
		        		{
		                    button6.setSelected(false);
		                    activeButton6 = null;
		                }
		                else
		                {	
		                	activeButton6 = button6;
		                	button6.setSelected(true);
		                }
				    }
			 });

			 
			 button7.setOnClickListener(new View.OnClickListener() 
			 {
				    @Override
				    public void onClick(View v)
				    {
				    	if (activeButton7 != null) 
		        		{
		                    button7.setSelected(false);
		                    activeButton7 = null;
		                }
		                else
		                {	
		                	activeButton7 = button7;
		                	button7.setSelected(true);
		                }
				    }
			});
		 
	}

    /********************************************************************************/

	
    
    private void traitement()
    {
    	TimePicker simpleTimePicker = (TimePicker) findViewById(R.id.timePicker);
	   	simpleTimePicker.setIs24HourView(true); // not display AM/PM mode
        
        button1 = (Button) findViewById(R.id.week_btn1);
        button2 = (Button) findViewById(R.id.week_btn2);
        button3 = (Button) findViewById(R.id.week_btn3);
        button4 = (Button) findViewById(R.id.week_btn4);
        button5 = (Button) findViewById(R.id.week_btn5);
        button6 = (Button) findViewById(R.id.week_btn6);
        button7 = (Button) findViewById(R.id.week_btn7);
        
        Calendar calendar = Calendar.getInstance();
        int current_day = calendar.get(Calendar.DAY_OF_WEEK);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        
        
    	Calendar cal_build_date = Calendar.getInstance();
    	cal_build_date.set(Calendar.YEAR, year);
    	cal_build_date.set(Calendar.DAY_OF_MONTH, day);
    	cal_build_date.set(Calendar.MONTH, month);
    	cal_build_date.set(Calendar.HOUR_OF_DAY, 0);
    	cal_build_date.set(Calendar.MINUTE, 0);
    	cal_build_date.set(Calendar.SECOND, 0);
    	cal_build_date.set(Calendar.MILLISECOND, 0);
        Date Date_date =  cal_build_date.getTime();
        long timestamp_current_date = cal_build_date.getTimeInMillis();
	
        
        //cal_build_date.add(Calendar.DAY_OF_MONTH, 3);
        //long toto = cal_build_date.getTimeInMillis();
       // Calendar cal_build_date = Calendar.getInstance();
    	
        
        // samedi 7       Sat
        // dimanche 1     Sun
        // lundi 2        Mon
        // mardi 3        Thues
        // mercredi 4     Wednes
        // jeudi 5		  Thurs
        // vendredi 6	  Fri	
        
        
        long timestamp_day = 60 * 60 * 24 * 1000; 
        long  timestamp_repeat = 0;
        long toto = 0;
        Date netDate = null;
        String aaa = "";
        SimpleDateFormat sdf = new SimpleDateFormat("EEE dd MM yyyy");

        
        int hours = 13;
        int minutes = 47;
        long timestamp = hours * ( 60 * 60 * 1000) +   minutes * (60 * 1000 )  ; 

        //  current_day  
        int repeat_day = 5;  // Jeudi 5   
       
        
        if(current_day < repeat_day)
        {
        	int diff_day = repeat_day - current_day;
        	timestamp_repeat = timestamp_current_date + (diff_day * timestamp_day) + timestamp ;
            netDate = (new Date(timestamp_repeat));
            aaa =  sdf.format(netDate);
        	
        	//cal_build_date.add(Calendar.DATE, -1);
            //Date_date =  cal_build_date.getTime();
            //cal_build_date.add(Calendar.DAY_OF_MONTH, 3);
            //Date_date =  cal_build_date.getTime();
            //toto = cal_build_date.getTimeInMillis();
        }
        
        timestamp_current_date = 1491343200000L;
        current_day = 4; // Mer
        repeat_day = 2;  // Lun    
        
        //Mercredi 5 Avril  = 1491343200000 
        
        if(current_day > repeat_day)
        {
            int step = 7 - current_day + repeat_day;
        	timestamp_repeat = timestamp_current_date + (step * timestamp_day) + timestamp ;
        	netDate = (new Date(timestamp_repeat));
            aaa =  sdf.format(netDate);
        }
        
        
        
        current_day = 1; // Dim
        repeat_day = 7;  // Sam    
        
        //Mercredi 5 Avril  = 1491343200000 
        
        
        	int diff_day = repeat_day - current_day;

            timestamp_current_date = 1491084000000L;
        	timestamp_repeat = timestamp_current_date + (diff_day * timestamp_day) + timestamp ;
        	netDate = (new Date(timestamp_repeat));
            aaa =  sdf.format(netDate);
        
            
        current_day = 1; // Dim
        repeat_day =  1;  // DIM    
        
    	long now = System.currentTimeMillis();
    	int zzz = 0;

        
        if(current_day == repeat_day)
        {
        	timestamp_repeat = timestamp_current_date + timestamp ;
            netDate = (new Date(timestamp_repeat));
            aaa =  sdf.format(netDate);

			if(timestamp_repeat < now)
			{
				zzz = 5;
				
				// horaire dépasser 
				
				// a
			}
            
        }
        
        timestamp_repeat = timestamp_repeat + 0;
        
        int[] unsortIntArray = new int[] {7,5,4,6,1,2,3};
        Arrays.sort(unsortIntArray);
        
        
        Long time = new GregorianCalendar().getTimeInMillis();  //+24*60*60*1000;
        // samedi 7
        // dimanche 1
        // lundi 2
        // mardi 3
        // mercredi 4
        // jeudi 5
        // vendredi 6
        
        //charger_configuration();

    	
    	
    }
    
//	https://android--examples.blogspot.fr/2015/04/timepickerdialog-in-android.html
//	https://www.codota.com/android/methods/android.widget.TimePicker/setCurrentMinute/
    // dialogFragment

    //http://www.journaldev.com/9976/android-date-time-picker-dialog
    // http://www.techiecommunity.net/Android/android-TimePickerDialog-example
    // http://www.ahotbrew.com/android-timepicker-example/
    //https://examples.javacodegeeks.com/android/core/ui/timepicker/android-time-picker-example/
    
    // http://android-coding.blogspot.fr/2012/07/dialogfragment-with-interface-to-pass.html
    
    // http://www.androidbegin.com/tutorial/android-dialogfragment-tutorial/
    //http://www.appsrox.com/android/instachat/
    // https://www.learnhowtoprogram.com/android/user-interface-basics-637d41b1-35dc-400a-bcc3-65794760474d/working-with-simple-fragments-dialogfragment
    

    private LinearLayout createLayout(int iOrientation)
    {
			LinearLayout lay = new LinearLayout(this);		
			lay.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			lay.setOrientation(iOrientation);
			return lay;
	}
    
    
    private void layout()
    {
    	LinearLayout layMain = createLayout(LinearLayout.VERTICAL);  	
 		layMain.setPadding(8, 8, 8, 8);
 		
 		ScrollView scrollView= new ScrollView(this);
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);               
        
 		/**/
 		LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
 		ImageView imageView = new ImageView(this);
 		imageView.setImageResource(R.drawable.clock);
 		LayoutParams layoutParams=new LayoutParams(75, 75);
 	    layoutParams.setMargins(10,10,0,0);
 	    imageView.setLayoutParams(layoutParams);
 	    ll.addView(imageView);
        mainLayout.addView(ll);
        
        /**/
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        TextView tv = new TextView(this);
        tv.setText("Evenement");
        tv.setPadding(10, 10, 0, 0);
 	    ll.addView(tv);
        mainLayout.addView(ll);

        /**/
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        EditText titre = new EditText(this);
        titre.setId(TAG_TITRE);
        layoutParams=new LayoutParams(450, 75);
        titre.setLayoutParams(layoutParams);
        titre.setSingleLine(true);
        titre.setFilters(new InputFilter[] { new InputFilter.LengthFilter(20) });
 	    ll.addView(titre);
        mainLayout.addView(ll);

        /**/
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        Button btn_timer_dialog = new Button(this);
        btn_timer_dialog.setId(7755);
        btn_timer_dialog.setText("SET TIME");
        ll.addView(btn_timer_dialog);
        mainLayout.addView(ll);
        
        /**/
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        tv = new TextView(this);
        tv.setId(TAG_TIME); 
        String tmp = "Time : " + "-- : --";
        tv.setText(tmp);
        tv.setPadding(10, 30, 0, 30);
        /**/
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
/******************** option alarme *************************/        
 	    
        final RadioGroup rg = new RadioGroup(getApplicationContext());
        rg.setOrientation(RadioGroup.HORIZONTAL);
        rg.setId(1234);
        RadioButton rb_ringtone = new RadioButton(getApplicationContext());
        rb_ringtone.setId(1678);
        rb_ringtone.setChecked(true);
        rb_ringtone.setText("Ringtone");
        rb_ringtone.setTextColor(Color.BLACK);
        rg.addView(rb_ringtone);
        RadioButton rb_vibrate = new RadioButton(getApplicationContext());
        rb_vibrate.setId(2678);
        rb_vibrate.setText("Vibrate");
        rb_vibrate.setTextColor(Color.BLACK);
        rg.addView(rb_vibrate);
        mainLayout.addView(rg);

/******************** Bouton *************************/        
        
        ll = new LinearLayout(this);
       	ll.setOrientation(LinearLayout.VERTICAL);
       	ll.setTag(9); 
        /**/
       	final View childView = getLayoutInflater().inflate(R.layout.weeks_button_layout, null);
        /**/
        ll.addView(childView);
        mainLayout.addView(ll);

        
/******************** Interval *************************/        
        
        
/******************** Bouton *************************/        
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setPadding(0, 30, 0, 0);
        ll.setGravity(Gravity.CENTER);
       
        Button b1 = new Button(this);
        b1.setId(1);
        b1.setText("Create");
        ll.addView(b1);
        
        Button b2 = new Button(this);
        b2.setId(2);
        b2.setText("Exit");
        ll.addView(b2);

        mainLayout.addView(ll);
        
        /** appliquer le code dans la vue ***/
        scrollView.addView(mainLayout);
        layMain.addView(scrollView);
        setContentView(layMain);
        
        
        btn_timer_dialog = (Button) findViewById(7755);
        btn_timer_dialog.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 					//finish();
 			    	//Toast.makeText(getApplicationContext(), "Timer set" , Toast.LENGTH_SHORT).show();
 			    	
 			    	String DIALOG_TIME = "MainActivity.TimeDialog";
 			    	
 			    	//debug_fragment pipo = new debug_fragment();
 	                //pipo.show(getFragmentManager(), DIALOG_TIME);
 	                
 	                
 	               DialogFragment newFragment = new Fragment01();
 	               newFragment.show(getFragmentManager(),"TimePicker");
 	                
 	            }
 			    	
 				  //  DialogFragment newFragment = new TimePickerFragment();
 				  //  newFragment.show(getFragmentManager(), "timePicker");
 				
 	    });
        
        Button btn_apply = (Button) findViewById(1);
        btn_apply.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 					create_repeat();
 			    	finish();
 				}
 	    });
        
    
        
        Button btn_quitter = (Button) findViewById(2);
        btn_quitter.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 					finish();
// 					DialogFragment alertDialExample = new dialog_fragment();
// 	                alertDialExample.show(getFragmentManager(), "AlertDialogFragment");
 				}
 	    });
    	
    }
    
    private void create_repeat()
    {
			
    	   	EditText id_titre = (EditText) findViewById(TAG_TITRE);
    	   	String titre = id_titre.getText().toString();
    	
    	   	TextView id_time = (TextView) findViewById(TAG_TIME);
    	   	String time = id_time.getText().toString();
    	   	
    	   	
		 	long timestamp_start = 0;
		 	String interval = "hour";
		 	
		 	long now = System.currentTimeMillis();
		 	timestamp_start = now + (30 * 1000 ); // 30 sec
		 	long interval_val = 30 * 1000; // 30 s 
			
			long id = db.insert_repeat("titre1" ,  timestamp_start,  "days_list_name" , interval , "active", "no_vibrate", "ringtone" );
		 	
//			Intent service = new Intent(AddRepeat.this, RepeatService.class);
//			service.putExtra("ALARMID", id );   
//			service.putExtra("TIME", timestamp_start);
//			service.putExtra("INTERVAL", interval_val);
//			service.setAction(RepeatService.REPEAT);
//			startService(service);  
		
	
			
    	
    }
    
    private void sauver_configuration()
    {
    	// lire l'état des boutons
    	
    	if (activeButton1 != null)
 		{
    		days_list_name = days_list_name + "LUN "; // 2
    		days_list_num = days_list_num + "2 "; 	
    		array_days_config_valeur[0]= 2 ;
    		array_days_config_name [0]= "LUN";
 		}
    	
    	if (activeButton2 != null)
 		{
    		days_list_name = days_list_name + "MAR "; // 3
    		days_list_num = days_list_num + "3 "; 	
    		array_days_config_valeur[1]= 3 ;
    		array_days_config_name [1]= "MAR";
 		}
    	
    	if (activeButton3 != null)
 		{
    		days_list_name = days_list_name + "MER "; // 4
    		days_list_num = days_list_num + "4 "; 	
    		array_days_config_valeur[2]= 4 ;
    		array_days_config_name [2]= "MER";
 		}
    	
    	if (activeButton4 != null)
 		{
    		days_list_name = days_list_name + "JEU ";  // 5
    		days_list_num = days_list_num + "5 "; 	
    		array_days_config_valeur[3]= 5 ;
    		array_days_config_name [3]= "JEU";
 		}
    
    	if (activeButton5 != null)
 		{
    		days_list_name = days_list_name + "VEN ";  // 6
    		days_list_num = days_list_num + "6 "; 	
    		array_days_config_valeur[4]= 6 ;
    		array_days_config_name [4]= "VEN";
 		}
    	
    	if (activeButton6 != null)
 		{
    		days_list_name = days_list_name + "SAM ";   // 7
    		days_list_num = days_list_num + "7 "; 	
    		array_days_config_valeur[5]= 7 ;
    		array_days_config_name [5]= "SAM";
 		}
    	
    	if (activeButton7 != null)
 		{
    		days_list_name = days_list_name + "DIM";  // 1
    		days_list_num = days_list_num + "1"; 	
    		array_days_config_valeur[6]= 1 ;
    		array_days_config_name [6]= "DIM";
 		}
  
    	// supprimer les espaces left et right
    	days_list_name = days_list_name.trim();
    	
    	long id = db.insert_repeat("titre1" ,  123456,  days_list_name , "inverval", "status", "option_vibrate", "option_ringtone" );
    	id = db.insert_repeat("titre2" ,  4645,  days_list_name , "inverval", "status", "option_vibrate", "option_ringtone" );
    	id = db.insert_repeat("titre3" ,  10000,  days_list_name , "inverval", "status", "option_vibrate", "option_ringtone" );
    	id = db.insert_repeat("titre4" ,  5664,  days_list_name , "inverval", "status", "option_vibrate", "option_ringtone" );
	    
    	Toast.makeText(getApplicationContext(), "Sauvegarde de l'alarme repeat" , Toast.LENGTH_SHORT).show();

    }
    
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{ 
	    switch (item.getItemId()) 
	    {
	        case android.R.id.home:
	        		this.finish();
	        		return true;
	            default:
	            return super.onOptionsItemSelected(item);
	    }
	}

}

