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.Cursor;
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.Log;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
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 AddRepeat02 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;
    
	CheckBox un, deux, trois;
    
	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;
	
	static int TAG_CHK1 = 5265;
	static int TAG_CHK2 = 5266;
	static int TAG_CHK3 = 5267;
	
	int  TAG_SPINNER1 = 10000;
	int  TAG_SPINNER2 = 10100;
	int  TAG_SPINNER3 = 10200;
	int  TAG_MULTISELECT = 10300;
	
	
	long global_timestamp_current_date;
	long global_timestamp;
    
    @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();

		

    }    
    
    /********************************************************************************/
	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(int option)
    {
    	//TimePicker simpleTimePicker = (TimePicker) findViewById(R.id.timePicker);
	   	//simpleTimePicker.setIs24HourView(true); // not display AM/PM mode
    	
    	
    	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();
    	
    	
    	boolean check = validation(option, titre, time); //, startTime, endTime, start_hour ,start_minutes, end_hour , end_minutes);
	   	
	    if(check == true)
	    {
        
    	
		    	if(option == 1)
		    	{
					//Toast.makeText(AddRepeat02.this, "Option 1: Validate", Toast.LENGTH_LONG).show();
					Spinner spinner =(Spinner)findViewById(TAG_SPINNER1);
			 		String interval_string = spinner.getSelectedItem().toString();
			 		//int position = spinner.getSelectedItemPosition();   // inutile 
			 		interval_string = interval_string.replace(" min","");
				 	long interval_val =  20 * 1000;  // toutes les 20 szc   //  Long.valueOf(interval_string) * 60 * 1000;
				 	
				 	//insert_repeat(String titre, long time,  String days_list , String inverval, String status, String option_vibrate, String option_ringtone )

				 	long id = db.insert_repeat(titre ,  global_timestamp,  "days_list_name" , interval_string , "active", "no_vibrate", "ringtone" );
					Intent service = new Intent(AddRepeat02.this, RepeatService.class);
					service.putExtra("ALARMID", id );  
					service.putExtra("OPTION", "option1"); 
					service.putExtra("TIME", global_timestamp);
					service.putExtra("INTERVAL", interval_val);
					service.setAction(RepeatService.REPEAT);
					startService(service);  
			    	finish();
		    	    
		    	}
    	
    	
		    	if(option == 2)
		    	{
					Toast.makeText(AddRepeat02.this, "Option 2..", Toast.LENGTH_LONG).show();
		
		    		
		    		
		    	}
		    	
		    	if(option == 3)
		    	{
		    		// en fonction des jours
					Toast.makeText(AddRepeat02.this, "Option 3..", Toast.LENGTH_LONG).show();
		    		
//https://github.com/wongk/MultiSelectSpinner 
		    		
		    		multiselectspinner01 obj =(multiselectspinner01)findViewById(TAG_MULTISELECT);
		    		List<String> selected = obj.getSelectedStrings();
		    		StringBuffer result = new StringBuffer();
		    		for(int x = 0; x < selected.size(); x = x + 1) 
		    		{
		    			result.append( selected.get(x) );
		    		}	
		    		
		    		String str = result.toString();
		    		String[] string_day = { "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi" };  // 1 a 7 
		    		boolean test;
		    		String value_day = "";
		    		
		    		test = str.contains( string_day[0] );
		    		if(test == true)
		    		{
		    			value_day = value_day + "1 ";
		    		}
		    		test = str.contains( string_day[1] );
		    		if(test == true)
		    		{
		    			value_day = value_day + "2 ";
		    		}
		    		test = str.contains( string_day[2] );
		    		if(test == true)
		    		{
		    			value_day = value_day + "3 ";
		    		}
		    		test = str.contains( string_day[3] );
		    		if(test == true)
		    		{
		    			value_day = value_day + "4 ";
		    		}
		    		test = str.contains( string_day[4] );
		    		if(test == true)
		    		{
		    			value_day = value_day + "5 ";
		    		}
		    		test = str.contains( string_day[5] );
		    		if(test == true)
		    		{
		    			value_day = value_day + "6 ";
		    		}
		    		test = str.contains( string_day[6] );
		    		if(test == true)
		    		{
		    			value_day = value_day + "7";
		    		}
		    		

		    		int l = value_day.length();
		    		value_day = value_day.trim();
		    		l = value_day.length();
		    		long day_interval = 24*60*60*1000;	
		    		
		    		long id = db.insert_repeat(titre ,  global_timestamp,  value_day , "interval_string" , "active", "no_vibrate", "ringtone" );
					Intent service = new Intent(AddRepeat02.this, RepeatService.class);
					service.putExtra("ALARMID", id );   
					service.putExtra("OPTION", "option3");   
					service.putExtra("TIME", global_timestamp);
					//service.putExtra("INTERVAL", "day"); //  AlarmManager.INTERVAL_DAY
					
					service.putExtra("INTERVAL", day_interval);
					service.setAction(RepeatService.REPEAT);
					startService(service);  
			    	finish();
		    		
			    	
		    		
		    	}
	    }
    	
    }
    
//	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
    
    
  //https://developer.android.com/training/scheduling/alarms.html
	// https://github.com/SheldonNeilson/Android-Alarm-Clock	
	// https://github.com/ben8p/android-poweralarm
	// Set Repeating Alarm Every Day at Specific time In Android
	// http://stacktips.com/tutorials/android/repeat-alarm-example-in-android
	// daily notification
	// http://android-er.blogspot.fr/2010/10/schedule-repeating-alarm.html
	// http://www.programering.com/a/MjM1YzMwATk.html
	// http://www.compiletimerror.com/2015/02/how-to-make-alarm-repeat-in-android-code.html
			    		
	//http://www.allappsdevelopers.com/TopicDetail.aspx?TopicID=a2dcfbc6-adf1-40b6-8884-3b886c5fb7b1 +++++++++++++++++++++++++++++++		    		
			    		
			    		
	//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startUpTime, AlarmManager.INTERVAL_DAY, pendingIntent);
	//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent); //Repeat every 24 hours
	

    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);

/******************** Set time *************************/        

        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);
        
        
/******************** Interval *************************/        

        ll = new LinearLayout(this);
       	ll.setOrientation(LinearLayout.HORIZONTAL);
        CheckBox checkBox1 = new CheckBox(this); 
        checkBox1.setId(TAG_CHK1);
        checkBox1.setChecked(true); 		       // selection par défaut 
        checkBox1.setPadding(10, 10, 0, 0);
    	ll.addView(checkBox1);
    	TextView tv_one = new TextView(this);
    	tv_one.setPadding(20, 10, 0, 0);
    	tv_one.setText("Frequency : ");
    	ll.addView(tv_one);
    	
    	final Spinner Spinner_opt4 = new Spinner(this);  
 	    Spinner_opt4.setId(TAG_SPINNER1);
 	    Spinner_opt4.setPadding(30, 10, 0, 10);
        layoutParams=new LayoutParams(125, 75);
        layoutParams.width += 50;  //
        Spinner_opt4.setLayoutParams(layoutParams);
        List<String> ArraySpinner_opt4 = new ArrayList<String>();
        //ArraySpinner_opt4.add("None");
        //ArraySpinner_opt4.add("Every Day");
        //ArraySpinner_opt4.add("Every Week");     
        //ArraySpinner_opt4.add("Every Month");
        //ArraySpinner_opt4.add("Every Year");
        
        ArraySpinner_opt4.add("2 min");
        ArraySpinner_opt4.add("10 min");
        ArraySpinner_opt4.add("15 min");     
        ArraySpinner_opt4.add("20 min");
        ArraySpinner_opt4.add("25 min");
        ArraySpinner_opt4.add("30 min");
        ArraySpinner_opt4.add("35 min");     
        ArraySpinner_opt4.add("40 min");
        ArraySpinner_opt4.add("45 min");
        ArraySpinner_opt4.add("50 min");
        ArraySpinner_opt4.add("55 min");     
        ArraySpinner_opt4.add("60 min");
        
        
        
        final ArrayAdapter<String> spinnerArrayAdapter_opt4 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ArraySpinner_opt4);
        spinnerArrayAdapter_opt4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        Spinner_opt4.setAdapter(spinnerArrayAdapter_opt4);
        Spinner_opt4.setVisibility(View.VISIBLE); 
        ll.addView(Spinner_opt4);
        mainLayout.addView(ll);
        
        ll = new LinearLayout(this);
       	ll.setOrientation(LinearLayout.HORIZONTAL);
        CheckBox checkBox2 = new CheckBox(this); 
        checkBox2.setId(TAG_CHK2);
        checkBox2.setPadding(10, 10, 0, 0);
    	ll.addView(checkBox2);
    	TextView tv_two = new TextView(this);
    	tv_two.setPadding(20, 10, 0, 0);
    	tv_two.setText("Interval2 : ");
    	ll.addView(tv_two);
    	final Spinner Spinner_opt5 = new Spinner(this);  
 	    Spinner_opt5.setId(TAG_SPINNER2);
 	    Spinner_opt5.setPadding(30, 10, 0, 10);
        layoutParams=new LayoutParams(125, 75);
        layoutParams.width += 50;  //
        Spinner_opt5.setLayoutParams(layoutParams);
        List<String> ArraySpinner_opt5 = new ArrayList<String>();
        ArraySpinner_opt5.add("2 min");
        ArraySpinner_opt5.add("10 min");
        ArraySpinner_opt5.add("15 min");     
        ArraySpinner_opt5.add("20 min");
        ArraySpinner_opt5.add("25 min");
        ArraySpinner_opt5.add("30 min");
        ArraySpinner_opt5.add("35 min");     
        ArraySpinner_opt5.add("40 min");
        ArraySpinner_opt5.add("45 min");
        ArraySpinner_opt5.add("50 min");
        ArraySpinner_opt5.add("55 min");     
        ArraySpinner_opt5.add("60 min");
        
        
        final ArrayAdapter<String> spinnerArrayAdapter_opt5 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ArraySpinner_opt5);
        spinnerArrayAdapter_opt5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        Spinner_opt5.setAdapter(spinnerArrayAdapter_opt5);
        Spinner_opt5.setVisibility(View.INVISIBLE); 
        ll.addView(Spinner_opt5);
        mainLayout.addView(ll);
      
        
        
        ll = new LinearLayout(this);
       	ll.setOrientation(LinearLayout.HORIZONTAL);
        CheckBox checkBox3 = new CheckBox(this); 
        checkBox3.setId(TAG_CHK3);
        checkBox3.setPadding(10, 10, 0, 0);
    	ll.addView(checkBox3);
    	TextView tv_tree = new TextView(this);
    	tv_tree.setPadding(20, 10, 0, 0);
    	tv_tree.setText("Days : ");
    	ll.addView(tv_tree);
        //String[] string_day = { "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche" };
        String[] string_day = { "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi" };  // 1 a 7 
        final multiselectspinner01 mySpin02 = new multiselectspinner01(this); 
        mySpin02.setId(TAG_MULTISELECT);
        mySpin02.setItems(string_day);
        mySpin02.setPadding(70, 10, 0, 10); // 30
        layoutParams=new LayoutParams(125, 75);
        layoutParams.width += 50;  //
        mySpin02.setLayoutParams(layoutParams);
        mySpin02.setVisibility(View.INVISIBLE); 
        ll.addView(mySpin02);
        mainLayout.addView(ll);
        

/******************** Bouton days *************************/        
        
    //  ll = new LinearLayout(this);
    // 	ll.setOrientation(LinearLayout.VERTICAL);
    // 	final View childView = getLayoutInflater().inflate(R.layout.weeks_button_layout, null);
    //  ll.addView(childView);
     // 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.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 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) 
 				{
 					if(un.isChecked())
 					{	
 						traitement(1);
 					}
 					
 					if(deux.isChecked())
 					{	
 						//traitement(2);
 					}
 					
 					if(trois.isChecked())
 					{	
 						traitement(3);
 					}
 					//traitement();
 					//create_repeat();
 				}
 	    });
        
    
        
        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");
 				}
 	    });
        
 
        
        un =(CheckBox)findViewById(TAG_CHK1);
        deux =(CheckBox)findViewById(TAG_CHK2);
        trois =(CheckBox)findViewById(TAG_CHK3);

        
        un.setOnClickListener(new OnClickListener()
        {
             public void onClick(View v)
             {
            	 if(un.isChecked())
            	 {
            		  Spinner_opt4.setVisibility(View.VISIBLE); 
            		  Spinner_opt5.setVisibility(View.INVISIBLE); 
            		  mySpin02.setVisibility(View.INVISIBLE); 
            		  deux.setChecked(false);
            		  trois.setChecked(false);
            	 }
            	 else // si on décoche, on restaure l'état cocher
            	 {
            		  un.setChecked(true);
            	 }
             }
        });
       
        
        deux.setOnClickListener(new OnClickListener()
        {
             public void onClick(View v)
             {
            	 if(deux.isChecked())
            	 {
            		  Spinner_opt4.setVisibility(View.INVISIBLE); 
            		  Spinner_opt5.setVisibility(View.VISIBLE); 
            		  mySpin02.setVisibility(View.INVISIBLE); 
            		  un.setChecked(false);
            		  trois.setChecked(false);
            	 }
            	 else // si on décoche, on restaure l'état cocher
            	 {
            		  deux.setChecked(true);
            	 }
             }
        });
        
        trois.setOnClickListener(new OnClickListener()
        {
             public void onClick(View v)
             {
            	 if(trois.isChecked())
            	 {
            		  Spinner_opt4.setVisibility(View.INVISIBLE); 
            		  Spinner_opt5.setVisibility(View.INVISIBLE); 
            		  mySpin02.setVisibility(View.VISIBLE); 
            		  un.setChecked(false);
            		  deux.setChecked(false);
            	 }
            	 else // si on décoche, on restaure l'état cocher
            	 {
            		  trois.setChecked(true);
            	 }
             }
        });
    	
   /*     
        Spinner sps =(Spinner)findViewById(TAG_SPINNER1);
        
        
        sps.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
            {
               int a = 0;
               a = 88;
               
               Toast.makeText(getBaseContext(), "titi",  Toast.LENGTH_LONG).show();                                                 
               
               String aaa = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //Another interface callback
            }
        });
        
  /*      
        sps.setOnItemSelectedListener(new OnItemSelectedListener()
        {
                    public void onItemSelected(AdapterView<?> arg0, View arg1,   int arg2, long arg3)
			        {
			        Toast.makeText(getBaseContext(), sp.getSelectedItem().toString(),
			        Toast.LENGTH_LONG).show();                                                 
			         }
                     public void onNothingSelected(AdapterView<?> arg0)
                     {
                                                // TODO Auto-generated method stub                 
                                                        }
        			});
    */    
    	
    }
    
    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();
    	   	
    	   	
	 		Spinner spinner =(Spinner)findViewById(TAG_SPINNER1);
	 		String valeur = spinner.getSelectedItem().toString();
	 		int position = spinner.getSelectedItemPosition();

    	   	
	        //boolean check = validation(titre); //, startTime, endTime, start_hour ,start_minutes, end_hour , end_minutes);
	        
	        //if(check == true)
	        //{
				 	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 
					
		//		 	insert_repeat(String titre, long time,  String days_list , String inverval, String status, String option_vibrate, String option_ringtone )
				 	
		//			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);  
				 	
		//	    	finish();
		 	
		
	     //   }	
			
    	
    }
    
    
    
    public boolean validation(int option, String titre, String startTime)  //,long startTime, long endTime, int start_hour , int start_minutes, int end_hour , int end_minutes)
	{
		
		 ArrayList<String> list_error = new ArrayList<String>();
		 
		 
		 if(option == 1)
		 {
			 
			 	if(titre.equals("") )
			 	{
			 		list_error.add("Pas de titre !!!");
			 		//return false;
			 		//	Toast.makeText(getApplicationContext(), "Vides ???", Toast.LENGTH_LONG).show();
			 	}
			 	
			 	if(startTime.equals("Time : -- : --") )
			 	{
			 			list_error.add("Timeset invalide !!!");
			 	}
			 	
			 	else
			 	{	
			    	
			 		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();
			 		global_timestamp_current_date = cal_build_date.getTimeInMillis();
			   	
			 		startTime = startTime.replace("Time : ","");
			 		String[] items = startTime.split(":");
			 		int heure = Integer.parseInt(items[0]);
			 		int min = Integer.parseInt(items[1]);
			 		global_timestamp = global_timestamp_current_date + heure * ( 60 * 60 * 1000) +   min * (60 * 1000 )  ; 
			 		
			 		long now = System.currentTimeMillis();
					if(global_timestamp <= now )
					{
						 list_error.add("Horaire dépassé !");
					}
		    	
			 	}
		 }
		 
		 
		 if(list_error.size() == 0 )
	     {	 
	     	 return true;
	     }
	     else
	     {
		        String toto = "";	
	    	 
	    	 	for(int x = 0; x <= list_error.size() - 1 ; x++)
	    	 	{
	    	   	 		toto = toto + list_error.get(x);
	    	   	 		toto = toto + System.getProperty("line.separator");
	    	 	}
	    	 	
		    	Toast.makeText(getApplicationContext(), toto, Toast.LENGTH_LONG).show();

		    	return false; 
	     }
		 
	}	 
    
    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);
	    }
	}

}

