package com.androidbegin.buttonclicktutorial;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.graphics.Color;
import android.app.ActionBar.LayoutParams;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

public class edit_infos_appointment extends Activity 
{
		CheckBox checkBox;
	
		TimeWidgetSlider start_timeSliderHour = null;
		TimeWidgetSlider start_timeSliderMinutes = null;
		TimeWidgetSlider end_timeSliderHour = null;
		TimeWidgetSlider end_timeSliderMinutes = null;
		
		private Button btnStartTime = null;
		private Calendar dateStart = null;
		
		private String date_event;
	    
	    LinearLayout layout1;
	    private static int viewsCount = 0;
	    private List<View> allViews = new ArrayList<View>();
	    LinearLayout.LayoutParams params;
	    
    
		private static String sStrSelect = "Select time";
		private static String sStrSet = "set";
		private static String sStrNone = "none";
		
		public static final int SELECT_TIME_REQUEST = 112;
		public static final int iSliderViewWidth = 276;
		private static final int iSmallButtonWidth = 100;	
		
		private LinearLayout layContent = null;
		private LinearLayout layContent2 = null;
		
		private Button btnNone = null;
		private Button btnOK = null;
		
		//fields
		private boolean bNoneButton = true;
		private boolean b24HourMode = false;
		private int start_hour = -1;
		private int start_minutes = -1;
		private int end_hour = -1;
		private int end_minutes = -1;
		
		private RelativeLayout mLayout;
		 
		String display_date = "";
		 
		int starthour;
		int startminute;
		int endhour; 
		int endminute;
		
		String date_selection;
		int index;
		
		DB_alarm db;
		appointment class_id = new appointment();
		
		String sid , titre,  start_timestamp , end_timestamp , phone , notes , option_delai, delai, option_vibrate, option_ringtone , status ,	 creation,  modification; 
		
		TextView tv_set_time_start;
		TextView tv_set_time_end;
		
	    static final int TIME_DIALOG_START = 1200;
	    static final int TIME_DIALOG_END = 1300;
	    	 
		int hour;
		int minute;
		
		int global_start_hour = 0; 
		int global_start_min = 0;

		int global_end_hour = 0; 
		int global_end_min = 0;

		String option_alarm;
		

		String id = "";
		
		CheckBox checkBox_option_delai;
		CheckBox checkBox_option_vibrate;
		CheckBox checkBox_option_ringtone;
		
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		  
		db = new DB_alarm(getApplicationContext());
		
        ActionBar actionBar = getActionBar();
        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("Edition du rendez-vous");
		
		Bundle extras = getIntent().getExtras();
		index = extras.getInt("index");
		date_selection = extras.getString("date_selection");
		
		//cal_display
		String[]tmp = date_selection.split(" ");
	    int jour = Integer.parseInt(tmp[0]);
	    int mois = Integer.parseInt(tmp[1]);
	    int annee = Integer.parseInt(tmp[2]);
	    mois = mois - 1;
	    Calendar cal = Calendar.getInstance();
	    cal.set(annee, mois, jour, 0, 0, 0); 
	    cal.set(Calendar.MILLISECOND, 0);
		
	    SimpleDateFormat formatter = new SimpleDateFormat("d MMMM, yyyy", Locale.ENGLISH);
        date_event = formatter.format(cal.getTime());

        /* lecture de la database*/
        
    	id = String.valueOf(index);
		String requete = "SELECT * FROM table_appointment WHERE _id = " + id ;
 	
		Cursor Cursor = db.DB_query(requete);
		int val = Cursor.getCount();
		
		if(val != 0)
		{
				if (Cursor.moveToFirst()) 
				{
 					do 
 					{
							sid = Cursor.getString(Cursor.getColumnIndex(DB_alarm.KEY_ID ));
	 						titre = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_TITRE ));
	 						start_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_START_TIME ));
	 						end_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_END_TIME ));
	 						phone = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_PHONE ));
	 						
	 						//option_delai = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_OPTION_DELAI ));
	 						option_delai = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_DELAI ));
	 						option_vibrate = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_OPTION_VIBRATE ));
	 						option_ringtone = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_OPTION_RINGTONE ));

	 						
	 						notes = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_NOTES ));
	 						status = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_STATUS ));
	 						creation = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_CREATEDTIME ));
	 						modification = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_MODIFIEDTIME ));
 					} while (Cursor.moveToNext());
 					
				}
		}
	
        
        /**/
        
		//class_id = MainActivity.appointment_DB.get(index-1);
		//titre = class_id.getTitre();
		//Date start_time = class_id.getStart_time(); 
		//Date end_time = class_id.getEnd_time(); 
		//phone =  class_id.getPhone(); 
		//notes = class_id.getNotes(); 
		
		
		//class_id = agenda02.appointment_liste.get(index-1);
		//titre = class_id.getTitre();
		//Date start_time = class_id.getStart_time(); 
		//Date end_time = class_id.getEnd_time(); 
		//phone =  class_id.getPhone(); 
		//notes = class_id.getNotes(); 
		
		Date start_time = new Date(Long.parseLong(start_timestamp));
		Date end_time = new Date(Long.parseLong(end_timestamp));

		
        //
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(start_time);
		starthour = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
		startminute = calendar.get(Calendar.MINUTE);
		calendar.setTime(end_time);
		endhour = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
		endminute = calendar.get(Calendar.MINUTE);
		
		
		layout();
			
	}
	
	
	public 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);               
        
/******************** Image *************************/    
        
 		LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(0); 
 		ImageView imageView = new ImageView(this);
 		imageView.setImageResource(R.drawable.appointment);
 		LayoutParams layoutParams=new LayoutParams(75, 75);
 	    layoutParams.setMargins(10,10,0,0);
 	    imageView.setLayoutParams(layoutParams);
 	    ll.addView(imageView);
        mainLayout.addView(ll);

/******************** Titre *************************/    
        
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(1); 
        TextView tv = new TextView(this);
        tv.setText("Evenementxxxxaqw");
        tv.setPadding(10, 10, 0, 0);
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(2); 
        final EditText editText = new EditText(this);
        editText.setId(150);
        //editText.setText("titre");
        layoutParams=new LayoutParams(450, 75);
        editText.setLayoutParams(layoutParams);
        editText.setSingleLine(true);
        editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(20) });
 	    ll.addView(editText);
        mainLayout.addView(ll);

/******************** Date *************************/    
        
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(3); 
 		/**/
        tv = new TextView(this);
        String tmp = "Date : " + date_event;
        tv.setText(tmp);
        tv.setPadding(10, 30, 0, 30);
        /**/
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
/******************** Heure *************************/    
        
        String str_starthour = pad(starthour); 
        String str_startminute = pad(startminute);
        
        String str_endhour = pad(endhour); 
        String str_endminute = pad(endminute);
        
        String start = str_starthour + ":" + str_startminute;
        String end = str_endhour + ":" + str_endminute;
        
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(4); 
        tv = new TextView(this);
        tv.setText("Start Time");
        tv.setPadding(10, 10, 0, 30);
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        tv_set_time_start = new TextView(this);
        tv_set_time_start.setText(start); 
        tv_set_time_start.setPadding(10, 10, 50, 30);
 	    ll.addView(tv_set_time_start);
 	    Button btn_start_time = new Button(this);
 	    btn_start_time.setId(144);
 	    btn_start_time.setText("Set");   
 	    ll.addView(btn_start_time);
        mainLayout.addView(ll);

 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(4); 
        tv = new TextView(this);
        tv.setText("End Time");
        tv.setPadding(10, 10, 0, 30);
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        tv_set_time_end = new TextView(this);
        tv_set_time_end.setText(end);
        tv_set_time_end.setPadding(10, 10, 50, 30);
 	    ll.addView(tv_set_time_end);
 	    Button btn_end_time = new Button(this);
 	    btn_end_time.setId(244);
 	    btn_end_time.setText("Set");   
 	    ll.addView(btn_end_time);
        mainLayout.addView(ll);
       
/******************** Alarme *************************/        
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(8); 
//        checkBox_option_delai = new CheckBox(this);
//        checkBox_option_delai.setId(800);
//        checkBox_option_delai.setText("Alarm");
//        checkBox_option_delai.setPadding(10, 10, 50, 10);
//	      ll.addView(checkBox_option_delai);

 	    
        tv = new TextView(this);
 	   	tv.setText("Delay");
       	tv.setPadding(10, 10, 0, 30);
	   	ll.addView(tv);

 	    
 	    //ViewGroup.LayoutParams params = mSomeView.getLayoutParams();
 	    //params.width += 10;
 	    //s1.setLayoutParams(params);
 	    
 	    final Spinner Spinner_alarm = new Spinner(this);  
        Spinner_alarm.setId(900);
        Spinner_alarm.setPadding(20, 10, 0, 10);
        layoutParams=new LayoutParams(125, 75);
        layoutParams.width += 50;  //
        Spinner_alarm.setLayoutParams(layoutParams);
        List<String> myArraySpinner = new ArrayList<String>();
        myArraySpinner.add("0min");
        myArraySpinner.add("15min");
        myArraySpinner.add("30min");
        myArraySpinner.add("1H");     
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, myArraySpinner);
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        Spinner_alarm.setAdapter(spinnerArrayAdapter);
        //Spinner_alarm.setVisibility(View.INVISIBLE); // hide
 	    ll.addView(Spinner_alarm);
        mainLayout.addView(ll);
/*        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(18); 
 	    checkBox_option_vibrate = new CheckBox(this);
 	    checkBox_option_vibrate.setId(850);
 	    checkBox_option_vibrate.setText("Vibrate");
 	    checkBox_option_vibrate.setPadding(20, 10, 50, 10);
 	    ll.addView(checkBox_option_vibrate);

 	    checkBox_option_ringtone = new CheckBox(this);
 	    checkBox_option_ringtone.setId(870);
 	    checkBox_option_ringtone.setText("Ringtone");
 	    checkBox_option_ringtone.setPadding(20, 10, 50, 10);
 	    ll.addView(checkBox_option_ringtone);
 	    mainLayout.addView(ll);
*/       
        
        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);

        
/******************** Phone *************************/        
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(9); 
        tv = new TextView(this);
        tv.setText("Phone");
        tv.setTag(50);
        tv.setPadding(10, 10, 0, 10);
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(10); 
        EditText editText_phone = new EditText(this);
        editText_phone.setId(100);
        //editText.setText(phone);
        layoutParams=new LayoutParams(300, 75);
        editText_phone.setLayoutParams(layoutParams);
        editText_phone.setSingleLine(true);
        editText_phone.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) });
        editText_phone.setInputType(InputType.TYPE_CLASS_PHONE);
 	    ll.addView(editText_phone);
 	    //mainLayout.addView(ll);
 	    
 	    //Button btn_phone = new Button(this);
 	    //btn_phone.setId(567);
 	    //btn_phone.setPadding(0,0,0,0);
 	    //btn_phone.setText("Call");
        //ll.addView(btn_phone);
        mainLayout.addView(ll);
		

/******************** Note *************************/        
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(8); 
        tv = new TextView(this);
        tv.setText("Notes");
        tv.setPadding(10, 10, 0, 10);
 	    ll.addView(tv);
        mainLayout.addView(ll);
		
        ll = new LinearLayout(this);
       	ll.setOrientation(LinearLayout.VERTICAL);
       	ll.setTag(9); 
       	final View childView = getLayoutInflater().inflate(R.layout.notes_view, null);
        ll.addView(childView);
        mainLayout.addView(ll);
 
/******************** Boutons *************************/        
           
       ll = new LinearLayout(this);
       ll.setOrientation(LinearLayout.HORIZONTAL);
       ll.setGravity(Gravity.CENTER);
       Button b1 = new Button(this);
       b1.setId(1);
       b1.setText("Sauver");
       ll.addView(b1);
       Button b2 = new Button(this);
       b2.setId(2);
       b2.setText("Delete");
       ll.addView(b2);
       Button b3 = new Button(this);
       b3.setId(3);
       b3.setText("Exit");
       ll.addView(b3);
       mainLayout.addView(ll);

/******************** Insert  la vue layout *************************/        
        
        scrollView.addView(mainLayout);
        layMain.addView(scrollView);
        setContentView(layMain);

/******************** Listeners  *************************/        
        
        ButtonListener();

/******************** Remplir les champs *************************/        
        
        EditText idtitre = (EditText)findViewById(150);  
        idtitre.setText(titre);
        
        final EditText idphone = (EditText)findViewById(100);  
        idphone.setText(phone);
        
        EditText idnotes = (EditText)findViewById(R.id.notes);  
        idnotes.setText(notes);
        
        int spinner_position = 0;
   	   	switch (option_delai) 
   	   	{
  					case "0": // 1000 * 60 * 15 
  						spinner_position = 0;
   						break;
	    	   		case "900000": // 1000 * 60 * 15 
	    	   			spinner_position = 1;
	   					break;
	   				case "1800000": // 1000 * 60 * 30
	   					spinner_position = 2;
	   					break;
	   				case "3600000": // 1000 * 60 * 60
	   					spinner_position = 3;
	   					break;
	   	}

	    // affectation    
	    Spinner_alarm.setSelection(spinner_position);
		
	    if(option_ringtone.equals("ringtone"))
		{
			rb_ringtone.setChecked(true);
			rb_vibrate.setChecked(false);
		}
		if(option_ringtone.equals("noringtone"))
		{
			rb_ringtone.setChecked(false);
			rb_vibrate.setChecked(true);
		}
	
		if(option_vibrate.equals("vibrate"))
		{
	        rb_vibrate.setChecked(true);
			rb_ringtone.setChecked(false);
		}
		if(option_vibrate.equals("novibrate"))
		{
	        rb_vibrate.setChecked(false);
			rb_ringtone.setChecked(true);
		}

		
/********************************************************************/
        
        Button btn_valider = (Button) findViewById(1);
        btn_valider.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
				  	
 					CharSequence time_start = tv_set_time_start.getText();
 					CharSequence time_end = tv_set_time_end.getText();
 					
 					String[] items1 = ((String) time_start).split(":");
 					start_hour = Integer.parseInt(items1[0]);
 					start_minutes = Integer.parseInt(items1[1]);
				  	
 					String[] items2 = ((String) time_end).split(":");
 					end_hour = Integer.parseInt(items2[0]);
 					end_minutes = Integer.parseInt(items2[1]);
				  	
				  	// creation des dates
				  	String[] items = date_selection.split(" ");
				  	// jour mois annee
				  	int jour = Integer.parseInt(items[0]);
				  	int mois = Integer.parseInt(items[1]);
				  	int annee = Integer.parseInt(items[2]);
				  	mois = mois - 1;
				  	
					Calendar cal_date = Calendar.getInstance();
					cal_date.set(Calendar.YEAR, annee);
					cal_date.set(Calendar.DAY_OF_MONTH, jour);
					cal_date.set(Calendar.MONTH, mois);
					cal_date.set(Calendar.HOUR_OF_DAY, 0);
					cal_date.set(Calendar.MINUTE, 0);
					cal_date.set(Calendar.SECOND, 0);
					cal_date.set(Calendar.MILLISECOND, 0);
			        Date Date_date =  cal_date.getTime();
			        long date = cal_date.getTimeInMillis();
				  			
				  	Calendar cal_start = Calendar.getInstance();
			        cal_start.set(annee,mois,jour,start_hour, start_minutes);
			        cal_start.set(Calendar.SECOND, 0);
			        cal_start.set(Calendar.MILLISECOND, 0);
			        Date Date_start =  cal_start.getTime();
			        long startTime = cal_start.getTimeInMillis();
			        
			    	Calendar cal_end = Calendar.getInstance();
			        cal_end.set(annee,mois,jour, end_hour, end_minutes);
			        cal_end.set(Calendar.SECOND, 0);
			        cal_end.set(Calendar.MILLISECOND, 0);
			        Date Date_end =  cal_end.getTime();
			        long endTime = cal_end.getTimeInMillis();
			        
			        String titre = editText.getText().toString();

			        EditText phone = (EditText)findViewById(100);  
			        String string_phone = phone.getText().toString();
			        
			        EditText notes = (EditText)findViewById(R.id.notes);  
			        String string_notes = notes.getText().toString();
			        
			    	// Arreter le service en cours
			    	String position_id = Integer.toString(index);
					Intent cancelThis = new Intent(edit_infos_appointment.this, AlarmService.class);
					long indice = Long.parseLong(position_id);   
					cancelThis.putExtra("ALARMID", indice );
					cancelThis.putExtra("TITRE", "");
 					cancelThis.putExtra("startTime", "");
					cancelThis.setAction(AlarmService.CANCEL);
					startService(cancelThis);
					
			    	Toast.makeText(getApplicationContext(), "Stop service", Toast.LENGTH_LONG).show();
					
			        boolean check = validation(titre, startTime, endTime);
				
			    	//boolean check = true;
			    	
			        if(check == true)
			        {	   
				        	  long option_delai_valeur = 0; 
				        		
				        	  int selectedId = rg .getCheckedRadioButtonId();
				        	
				        	  switch (selectedId) 
					    	  {
					    	   		case 1678: // ringtone
								    	String delai =Spinner_alarm.getSelectedItem().toString();
										option_ringtone = "ringtone";
										option_vibrate = "novibrate";
								    	   
								    	switch (delai) 
								    	{
								    	   		case "0min":
							   						option_delai_valeur = 0;
							   						break;
								   				case "15min":
								   					option_delai_valeur = 1000 * 60 * 15;
								   					break;
								   				case "30min":
								   					option_delai_valeur = 1000 * 60 * 30;
								   					break;
								   				case "1H":
								   					option_delai_valeur = 1000 * 60 * 60;
								   					break;
								    	}
				   						break;

					    	   		case 2678: // vibrate
										option_ringtone = "noringtone";
										option_vibrate = "vibrate";


					   					break;
					    	  } 

					        
					    	// mise a jour de la database
					    	//String position = Integer.toString(index);
					        long now = System.currentTimeMillis();
					        now = System.currentTimeMillis();
					    	ContentValues contentValues = new ContentValues();
					    	contentValues.put(DB_alarm.COL_TITRE, titre);
					    	contentValues.put(DB_alarm.COL_START_TIME, startTime);
					    	contentValues.put(DB_alarm.COL_END_TIME, endTime);
					    	contentValues.put(DB_alarm.COL_PHONE, string_phone);
					    	contentValues.put(DB_alarm.COL_NOTES, string_notes);
					    	//contentValues.put(DB_alarm.COL_OPTION_DELAI, option_delai);
					    	contentValues.put(DB_alarm.COL_DELAI, option_delai_valeur);
					    	contentValues.put(DB_alarm.COL_OPTION_VIBRATE, option_vibrate);
					    	contentValues.put(DB_alarm.COL_OPTION_RINGTONE, option_ringtone);
					    	contentValues.put(DB_alarm.COL_MODIFIEDTIME, now);
					        
					    	db.update_appoitment(position_id, contentValues);
					    	
					    	mois = mois + 1;
					        String dateInString = jour + "-" + mois +  "-" + annee + " " + start_hour + ":" + start_minutes;
							long  time_millis = Tools.convertir_date_timestamp(dateInString); 
							
							// prendre en compte le delai
							time_millis = time_millis - option_delai_valeur;

							// creation d'un nouveau service
							Intent service = new Intent(edit_infos_appointment.this, AlarmService.class);
							service.putExtra("ALARMID", id );              
							service.putExtra("TITRE", titre);
							service.putExtra("DELAI", option_delai_valeur);
							service.putExtra("option_delai", option_delai);
							service.putExtra("option_vibrate", option_vibrate);
							service.putExtra("option_ringtone", option_ringtone);
							service.putExtra("TIME", time_millis);
							service.setAction(AlarmService.POPULATE);
							startService(service);
					    	Toast.makeText(getApplicationContext(), "Modifications enregistrées", Toast.LENGTH_LONG).show();

							//OnClose();  
							//finish();
					    	
					    	// retour a mainactivity
					    	Intent i=new Intent(edit_infos_appointment.this ,MainActivity.class);
					    	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					    	startActivity(i);
							
////////////////////////// none used							
					    	// efface le service en cours
//							Intent cancelThis = new Intent(edit_infos_appointment.this, AlarmService.class);
//	 						long indice = Long.parseLong(position);   
//							cancelThis.putExtra("ALARMID", indice );
//							cancelThis.putExtra("ALARMID", sid);
//							cancelThis.putExtra("TITRE", "");
//		 					cancelThis.putExtra("startTime", "");
//							cancelThis.setAction(AlarmService.CANCEL);
//							startService(cancelThis);
							
							// creation d'un nouveau service
//				    		Intent service = new Intent(edit_infos_appointment.this, AlarmService.class);
//				    		service.putExtra("ALARMID", indice );              
//				    		service.putExtra("TITRE", titre);
//				    		service.putExtra("TIME", time_millis);
//				    		service.setAction(AlarmService.POPULATE);
//				    		startService(service);

				        	
			        }
			        
 				}
 	    });
        
        Button btn_supprimer = (Button) findViewById(2);
        btn_supprimer.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 					//Toast.makeText(getApplicationContext(), "Supprimer", Toast.LENGTH_LONG).show();
 					
 					delete_appointment();
 				}
 	    });
		
        
        Button btn_quitter = (Button) findViewById(3);
        btn_quitter.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 					finish();
 				}
 	    });
        
	}
/*	
	public void CheckBox_AlarmListener(final Spinner option_alarm)
	{
			checkBox = (CheckBox) findViewById(800);
	
			checkBox.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v)
				{
		                //is chkIos checked?
					if (((CheckBox) v).isChecked())
					{	 
						option_alarm.setVisibility(View.VISIBLE); 
						Toast.makeText(edit_infos_appointment.this, "Visible", Toast.LENGTH_LONG).show();
					}
					else
					{
						option_alarm.setVisibility(View.INVISIBLE); 
						Toast.makeText(edit_infos_appointment.this, "Invisible", Toast.LENGTH_LONG).show();
					}
				}
			});

	}
*/
	
/*	
	public void CheckBox_option_delai_Listener(final Spinner option_alarm)
	{
			checkBox_option_delai = (CheckBox) findViewById(800);
	
			checkBox_option_delai.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v)
				{
		                //is chkIos checked?
					if (((CheckBox) v).isChecked())
					{	 
						option_alarm.setVisibility(View.VISIBLE); 
						option_delai = "delai";
						Toast.makeText(edit_infos_appointment.this, "Visible", Toast.LENGTH_LONG).show();
					}
					else
					{
						option_alarm.setVisibility(View.INVISIBLE); 
						option_delai = "nodelai";
						Toast.makeText(edit_infos_appointment.this, "Invisible", Toast.LENGTH_LONG).show();
					}
				}
			});

	}
	
*/	
	
/*	
	public void CheckBox_option_vibrate_Listener()
	{
		
		checkBox_option_vibrate = (CheckBox) findViewById(850);
		
		checkBox_option_vibrate.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v)
			{
                //is chkIos checked?
				if (((CheckBox) v).isChecked())
				{	 
					Toast.makeText(edit_infos_appointment.this, "Vibrate", Toast.LENGTH_LONG).show();
					option_vibrate = "vibrate";
				}
				else
				{
					Toast.makeText(edit_infos_appointment.this, "Tranquille", Toast.LENGTH_LONG).show();
					option_vibrate = "novibrate";
				}
			}
		});

	}
*/    
/*
	public void CheckBox_option_ringtone_Listener()
	{
		
		checkBox_option_ringtone = (CheckBox) findViewById(870);
		
		checkBox_option_ringtone.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v)
			{
                //is chkIos checked?
				if (((CheckBox) v).isChecked())
				{	 
					Toast.makeText(edit_infos_appointment.this, "Ringtone", Toast.LENGTH_LONG).show();
					option_ringtone = "ringtone";
				}
				else
				{
					Toast.makeText(edit_infos_appointment.this, "NoRingtone", Toast.LENGTH_LONG).show();
					option_ringtone = "noringtone";
				}
			}
		});

	}
*/
	

	public void ButtonListener() 
	{
		findViewById(144).setOnClickListener(mGlobal_OnClickListener);
		findViewById(244).setOnClickListener(mGlobal_OnClickListener);
	}
	
	
	//Global On click listener for all views
    OnClickListener mGlobal_OnClickListener = new OnClickListener()
    {
	        public void onClick(final View v)
	        {
	            switch(v.getId())
	            {
	                case 144:
						//Toast.makeText(AddEvent02.this, "un", Toast.LENGTH_LONG).show();
		                //showDialog(TIME_DIALOG_START);
	                	dialog_box_timepicker("Choice start Time", "start");
	                    break;
	                case 244:
	                    //Toast.makeText(AddEvent02.this, "Button2 clicked.", Toast.LENGTH_SHORT).show();
		                //showDialog(TIME_DIALOG_END);
	                	dialog_box_timepicker("Choice end Time", "end");
	                    break;
	            }
	        }
    };
    

	private void dialog_box_timepicker(String titre, final String action)
	{
	
		LayoutInflater inflater = getLayoutInflater();
		View alertLayout = inflater.inflate(R.layout.custom_datepicker_layout, null);
    
		final TimePicker tp = (TimePicker) alertLayout.findViewById(R.id.timePicker1);
		
		tp.setIs24HourView(true); 
		
		if(action.equals("start"))
		{
			tp.setCurrentHour(global_start_hour); 
			tp.setCurrentMinute(global_start_min);
		}
		else
		{
			tp.setCurrentHour(global_end_hour); 
			tp.setCurrentMinute(global_end_min);
		}
		
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(titre);
		// this is set the view from XML inside AlertDialog
		alert.setView(alertLayout);
		// disallow cancel of AlertDialog on click of back button and outside touch
		alert.setCancelable(false);
    
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
			}
		});

		alert.setPositiveButton("Set", new DialogInterface.OnClickListener() 
		{

			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				if(action.equals("start"))
				{	
					global_start_hour = tp.getCurrentHour();
					global_start_min = tp.getCurrentMinute();
	
					tv_set_time_start.setText(new StringBuilder().append(pad(global_start_hour))	.append(":").append(pad(global_start_min)));
				}
				else
				{
					global_end_hour = tp.getCurrentHour();
					global_end_min = tp.getCurrentMinute();
					tv_set_time_end.setText(new StringBuilder().append(pad(global_end_hour))	.append(":").append(pad(global_end_min)));
				}
			}
		});

		AlertDialog dialog = alert.create();
		dialog.show();
	}

	
	private static String pad(int c)
	{
		if (c >= 10)
		   return String.valueOf(c);
		else
		   return "0" + String.valueOf(c);
	}

	
	public boolean validation(String titre,long startTime, long endTime)
	{
		
		 ArrayList<String> list_error = new ArrayList<String>();

		 long now = System.currentTimeMillis();

		 if(startTime <= now )
		 {
			 list_error.add("Impossible de créer le rendez-vous: Horaire dépassé !");
		 }
		 
		 if(titre.equals("") )
	     {
			 list_error.add("Pas de titre !!!");
	         //Toast.makeText(getApplicationContext(), "Vides ???", Toast.LENGTH_LONG).show();
	     }

	     if (startTime >=  endTime)
	     {
	    	 list_error.add("Incohérence : fin avant le début !!!!");
        	 //Toast.makeText(getApplicationContext(), "Probléme Date !!!!", Toast.LENGTH_LONG).show();
	     }
	        
	        
	     if ( endTime - startTime < 1800000 ) // 30 min : 60 * 1000 * 30  = 1800000
	     {
	    	 list_error.add("Rendez-vous inférieur à 30min !!!");
	         //Toast.makeText(getApplicationContext(), "Rendez-vous inférieur à 30min !!! ", Toast.LENGTH_LONG).show();
	     }
	     
	     
	     boolean overlap = non_recouvrement(startTime, endTime);
	     if(overlap == true)
	     {
	    	 list_error.add("Attention overlap !!!");
	     }
	     
	     
	     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; 
	     }
	}
	
	/********************************************/
	public boolean non_recouvrement(long borne_startTime, long borne_endTime)
	{
  			// plage qui se chevauche - overlap
		
			SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy"); 
 	   	  	Date date = null;
 	   	  	try
 	   	  	{
 	   	  		date = sdf.parse(date_selection);
 	   	  	} 
 	   	  	catch (ParseException e)
 	   	  	{
				e.printStackTrace();
 	   	  	}
	      
 	   	  	long timestamp = date.getTime();
		 	String stimestamp = String.valueOf(timestamp);
		         
		    String requete = "SELECT * FROM table_appointment WHERE date = " + stimestamp + " AND _id != " + id ; // exclure la rendez_vous que l'on met a jour
		     	
		    //select * from tablename where column1 ='a' and column2!='b';
		    
		    Cursor Cursor = db.DB_query(requete);
		    int val = Cursor.getCount();
		   
		    boolean overlap = false;
		    
		    if(val != 0)
		    {
		    			if (Cursor.moveToFirst()) 
		 				{
			 					do 
			 					{
				 						String string_start_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_START_TIME ));
				 						String string_end_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_END_TIME ));
				 						
				 						
				 						long start_timestamp = Long.parseLong(string_start_timestamp);   
				 						long end_timestamp = Long.parseLong(string_end_timestamp);   
/*				 						
				 						if(borne_startTime == start_timestamp && borne_endTime == end_timestamp)
				 						{
				 					    	Toast.makeText(getApplicationContext(), "Unchange", Toast.LENGTH_LONG).show();

				 						}
				 						else
				 						{
				 								
					 						if(  borne_startTime >= start_timestamp && borne_startTime <= end_timestamp  )
					 						{
					 							overlap = true;
					 						}
					 						
					 						
					 						if(  borne_endTime >= start_timestamp && borne_endTime <= end_timestamp  )
					 						{
					 							overlap = true;
					 						}
					 						
					 						
					 						if( borne_startTime <=  start_timestamp && borne_endTime >= end_timestamp)
					 						{
					 							overlap = true;
					 						}
				 						
				 						}
*/				 						
				 						
				 						
				 						if(  borne_startTime >= start_timestamp && borne_startTime <= end_timestamp  )
				 						{
				 							overlap = true;
				 						}
				 						
				 						
				 						if(  borne_endTime >= start_timestamp && borne_endTime <= end_timestamp  )
				 						{
				 							overlap = true;
				 						}
				 						
				 						
				 						if( borne_startTime <=  start_timestamp && borne_endTime >= end_timestamp)
				 						{
				 							overlap = true;
				 						}
				 						
				 					
			 						
			 					} while (Cursor.moveToNext());
			 					
		 				}
		    			
		    			
		 		}
		    	
		    
		    	return overlap;
	}

	
	
	public void delete_appointment()
    {
    	
							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

							alertDialogBuilder.setTitle("Confirmation");
			
							// set dialog message
							alertDialogBuilder
							.setMessage("Click yes to delete !")
							.setCancelable(false)
							.setPositiveButton("Yes",new DialogInterface.OnClickListener()
							{
								public void onClick(DialogInterface dialog,int id)
								{
									Toast.makeText(getApplicationContext(), "Suppression du rendez-vous OK", Toast.LENGTH_LONG).show();
									//db.delete_appointment(sid); 
//				 					Intent cancelThis = new Intent(infos_appointment.this, AlarmService.class);
//				 					cancelThis.putExtra("ALARMID", String.valueOf(index));
//				 					cancelThis.putExtra("TITRE", "");
//				 					cancelThis.putExtra("startTime", "");
//				 					cancelThis.setAction(AlarmService.CANCEL);
//				 					startService(cancelThis);

									
									
									//db.cancelNotification(sid);
									
									db.delete_appointment(sid);
									Intent cancelThis = new Intent(edit_infos_appointment.this, AlarmService.class);
									
			 						long indice = Long.parseLong(sid);   

									
									cancelThis.putExtra("ALARMID", indice );
									//cancelThis.putExtra("ALARMID", sid);
				 					
									cancelThis.putExtra("TITRE", "");
				 					cancelThis.putExtra("startTime", "");
									cancelThis.setAction(AlarmService.CANCEL);
									startService(cancelThis);
									
									String coco = "5";
									int a = coco.length();
									
									finish();
									
									//refresh = true;

									
								}
							})
							
							.setNegativeButton("No",new DialogInterface.OnClickListener()
							{
								public void onClick(DialogInterface dialog,int id)
								{
									dialog.cancel();
									//Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
								}
							});

							// create alert dialog
							AlertDialog alertDialog = alertDialogBuilder.create();

							// show it
							alertDialog.show();
    }
	
	
	
	public LinearLayout createLayout(int Orientation)
	{
			LinearLayout lay = new LinearLayout(this);		
			lay.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			lay.setOrientation(Orientation);
			return lay;
	}
	
	
/*	
	final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

	for (int i = 0; i < recentTasks.size(); i++) 
	{
	    Log.d("Executed app", "Application executed : " +recentTasks.get(i).baseActivity.toShortString()+ "\t\t ID: "+recentTasks.get(i).id+"");         
	}
*/	
	
	
	//http://techblogon.com/get-running-applications-list-in-android-example/
	
}