package com.example.db01;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter.ViewBinder;

import java.nio.channels.*;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.io.FileWriter;



public class MainActivity extends ListActivity
{
		
		private SimpleCursorAdapter dataAdapter;
		public final Calendar cal = Calendar.getInstance();
		public final Date dt = new Date();
		
		public static final String PREFERENCES_NAME = "MyPrefsFile";
		
		private TextView rangeText;
		public static SharedPreferences sp;
		
		public static final String TIME_OPTION = "time_option";
		public static final String DATE_RANGE = "date_range";
		public static final String DATE_FORMAT = "date_format";
		public static final String TIME_FORMAT = "time_format";
		public static final String VIBRATE_PREF = "vibrate_pref";
		public static final String RINGTONE_PREF = "ringtone_pref";
		public static final String DEFAULT_DATE_FORMAT = "yyyy-M-d";
		
		public static final String REQUEST_CODE = "passage";
		
		String[] monthArr = new String[]{ "Month","Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"  };
		
		DB_alarm db;
		private SQLiteDatabase dataBase;
		
		private AlertDialog disclaimer;
		
		final String EXTRA_POSITION = "extra_position";
		final String EXTRA_ID = "extra_id";

		@Override
		public void onCreate(Bundle savedInstanceState)
		{
			 	super.onCreate(savedInstanceState);
			 	setContentView(R.layout.activity_main);
		        db = new DB_alarm(getApplicationContext());
		        
		    	PreferenceManager.setDefaultValues(this, R.xml.settings, false);
				sp = PreferenceManager.getDefaultSharedPreferences(this);
				
				
			//	SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
	    	//	String zorro = sp.getString(DATE_RANGE, null);
	    		
	    	//	SettingsActivity.retourne();
	    		
	    		//Preference pref = findPreference(SettingsActivity.DATE_RANGE);
	    		//SettingsActivity.findPreference("pref_key");
				
				
				rangeText = (TextView) findViewById(R.id.range_tv);
				
				int r = Tools.getDateRange();
				
				switch(r)
				{
					case 3: // Yearly
						cal.set(Calendar.MONTH, 0);
						
					case 2: // Monthly
						cal.set(Calendar.DATE, 1);
						
					case 1: // Weekly
						if (r==1)
						{	cal.set(Calendar.DATE, cal.getFirstDayOfWeek());
							//cal.set(Calendar.DATE, 1);
						}
						
					case 0: // Daily
				        cal.set(Calendar.HOUR_OF_DAY, 0);
				    	cal.set(Calendar.MINUTE, 0);
						cal.set(Calendar.SECOND, 0);
						cal.set(Calendar.MILLISECOND, 0);
				}
				
				//creation_alarm();
			 	
			 	registerForContextMenu(getListView());
		}
		
		

		@Override
		protected void onSaveInstanceState(Bundle outState)
		{
			super.onSaveInstanceState(outState);
			outState.putLong("cal", cal.getTimeInMillis());
		}	

		@Override
		protected void onRestoreInstanceState(Bundle state)
		{
			super.onRestoreInstanceState(state);
			cal.setTimeInMillis(state.getLong("cal"));
		}
		
		private void creation_alarm()
		{
	       
			String dateInString = "28-11-2016 22:00";
			long  time_millis = Tools.convertir_date_timestamp(dateInString);
		    long now = System.currentTimeMillis(); 
		    String NAME = "28-11-2016";
		    String FROMDATE =  "un_a";
		    String TODATE =  "un_b";
		    long DATETIME =  time_millis;
		    String STATUS = "active";
		    long CREATEDTIME =  now ;
		    long MODIFIEDTIME =  now ;
		    db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
		   
		    dateInString = "11-11-2016 17:49";
			time_millis = Tools.convertir_date_timestamp(dateInString);
		    now = System.currentTimeMillis(); 
		    NAME = "11-11-2016";
		    FROMDATE =  "deux_a";
		    TODATE =  "deux_b";
		    DATETIME =  time_millis;
		    STATUS = "active";
		    CREATEDTIME =  now ;
		    MODIFIEDTIME =  now ;
		    db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
		    
		    dateInString = "17-12-2016 11:11";
			time_millis = Tools.convertir_date_timestamp(dateInString);
		    now = System.currentTimeMillis(); 
		    NAME = "17-12-2016";
		    FROMDATE =  "deux_a";
		    TODATE =  "deux_b";
		    DATETIME =  time_millis;
		    STATUS = "active";
		    CREATEDTIME =  now ;
		    MODIFIEDTIME =  now ;
		    db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
			
		    dateInString = "15-9-2016 12:30";
			time_millis = Tools.convertir_date_timestamp(dateInString);
		    now = System.currentTimeMillis(); 
		    NAME = "15-9-2016";
		    FROMDATE =  "deux_a";
		    TODATE =  "deux_b";
		    DATETIME =  time_millis;
		    STATUS = "active";
		    CREATEDTIME =  now ;
		    MODIFIEDTIME =  now ;
		    db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
		   
		    dateInString = "15-12-2016 0:30";
			time_millis = Tools.convertir_date_timestamp(dateInString);
		    now = System.currentTimeMillis(); 
		    NAME = "15-12-2016";
		    FROMDATE =  "trois_a";
		    TODATE =  "trois_b";
		    DATETIME =  time_millis;
		    STATUS = "active";
		    CREATEDTIME =  now ;
		    MODIFIEDTIME =  now ;
		    db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
		    
		    dateInString = "25-12-2016 14:23";
			time_millis = Tools.convertir_date_timestamp(dateInString);
		    now = System.currentTimeMillis(); 
		    NAME = "25-12-2016";
		    FROMDATE =  "trois_a";
		    TODATE =  "trois_b";
		    DATETIME =  time_millis;
		    STATUS = "active";
		    CREATEDTIME =  now ;
		    MODIFIEDTIME =  now ;
		    db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
		    
		    dateInString = "8-1-2017 12:45";
		 	time_millis = Tools.convertir_date_timestamp(dateInString);
		 	now = System.currentTimeMillis(); 
		 	NAME = "8-1-2017";
		 	FROMDATE =  "trois_a";
		 	TODATE =  "trois_b";
		 	DATETIME =  time_millis;
		 	STATUS = "active";
		 	CREATEDTIME =  now ;
		 	MODIFIEDTIME =  now ;
		 	db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);

		}
		
		
		
		private String move(int step) 
		{
			switch(Tools.getDateRange()) 
			{
				case 0:
					cal.add(Calendar.DATE, 1*step); // jour
					break;		
				case 1:
					cal.add(Calendar.DATE, 7*step); // semaine = 7 jours
					break;
				case 2:
					cal.add(Calendar.MONTH, 1*step); // mois
					cal.set(Calendar.DATE, 1);  // premier jour du mois   
					
					break;
				case 3:
					cal.add(Calendar.YEAR, 1*step); // année
					break;			
			}
			return "";
		}    
		
		/********************/
/*		
		private Cursor createCursor()
		{
			Cursor c = dbHelper.listNotifications(cal.getTimeInMillis()+move(+1), cal.getTimeInMillis()+move(-1));
			//startManagingCursor(c);
			return c;
		}
		
		
		@Override
		protected void onResume() 
		{
			super.onResume();

			SimpleCursorAdapter adapter = new SimpleCursorAdapter(
									this, 
									R.layout.row, 
									createCursor(), 
									new String[]{Alarm.COL_NAME, AlarmMsg.COL_DATETIME, AlarmMsg.COL_DATETIME, AlarmMsg.COL_DATETIME, AlarmMsg.COL_DATETIME}, 
									new int[]{R.id.msg_tv, R.id.year_tv, R.id.month_tv, R.id.date_tv, R.id.time_tv},0);
			
			final Calendar calendar = Calendar.getInstance();
			//calendar.setTime(time);
			
			adapter.setViewBinder(new ViewBinder() 
			{
				@Override
				public boolean setViewValue(View view, Cursor cursor, int columnIndex) 
				{
						if (view.getId() == R.id.msg_tv) return false;
	
						TextView tv = (TextView)view;
						long time = cursor.getLong(columnIndex);
						//dt.setTime(time);
						
						 Date date = new Date(time);
						 calendar.setTime(date);
						
						switch(view.getId()) 
						{
							case R.id.year_tv:
								int year = calendar.get(Calendar.YEAR);
								tv.setText(String.valueOf(year));  
								//tv.setText(String.valueOf(dt.getYear()+1900));  
								break;
							case R.id.month_tv:
								tv.setText(monthArr[ calendar.get(Calendar.MONTH) +1]);
								//tv.setText(monthArr[dt.getMonth()+1]);
								break;
							case R.id.date_tv:
								tv.setText(String.valueOf( calendar.get(Calendar.DATE) ) );
								//tv.setText(String.valueOf(dt.getDate()));
								break;
							case R.id.time_tv:
								long now = System.currentTimeMillis();
								//String txt = RemindMe.showRemainingTime() ? Utils.getRemainingTime(time, now) : Utils.getActualTime(dt.getHours(), dt.getMinutes());
								//if (TextUtils.isEmpty(txt)) txt = Util.getActualTime(dt.getHours(), dt.getMinutes());
								
								String res = Utils.getRemainingTime(time, now);
								tv.setText(res);
								RelativeLayout parent = (RelativeLayout)tv.getParent();
								TextView tv2 = (TextView) parent.findViewById(R.id.msg_tv);
								if (time < now) tv2.setTextColor(Color.parseColor("#555555"));
								else tv2.setTextColor(Color.parseColor("#587498"));
								break;
								
						}
						return true;
				}
			});
			
			setListAdapter(adapter);
			rangeText.setText(getRangeStr());
			
		}
*/
		
		private Cursor createCursor()
		{
			dataBase = db.getWritableDatabase();
			String TAG = " ****************** ";
			 
	 		long temps_actuel = 0;
	 		temps_actuel = 	cal.getTimeInMillis();
	 		String max = cal.getTimeInMillis() + move(+1);
	 		String min = cal.getTimeInMillis() + move(-1);
	 		
	 		Calendar cal_tmp = Calendar.getInstance();
	 		
	 		long d1 = Long.parseLong(max);
			cal_tmp.setTimeInMillis(d1);
			Date dt1 = cal_tmp.getTime();
			Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String s1 = formatter.format(dt1);
			
			long d2 = Long.parseLong(min);
			cal_tmp.setTimeInMillis(d2);
			Date dt2 = cal_tmp.getTime();
			formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String s2 = formatter.format(dt2);

			Log.i(TAG, s1);
			Log.i(TAG, s2);
			
			//int jour = cal_tmp.get(Calendar.DATE);
			//String mois = monthArr[cal_tmp.get(Calendar.MONTH) +1 ];
			//int annee = cal_tmp.get(Calendar.YEAR);
			
			
			String requete = "SELECT * FROM table_alarm WHERE datetime >= " + max + " AND datetime <= " + min + " ORDER BY datetime ASC" ;
			Cursor mCursor = db.DB_query(requete);
			int val = mCursor.getCount();
			//String TAG = " ****************** ";
		    Log.i(TAG, String.valueOf(val));
			    
			return  mCursor;   
		}	
		
		
	  @Override
	  protected void onResume() 
	    {
			super.onResume();
			
			
			SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0); // 0 - for private mode
			Editor editor = pref.edit();
			
			String DATE_RANGE_CHANGE = pref.getString("DATE_RANGE_CHANGE", null); 
			Toast.makeText(getApplicationContext(), DATE_RANGE_CHANGE, Toast.LENGTH_LONG).show();

			
			//int i = pref.getInt("deux", 0); 
			//Boolean etat =pref.getBoolean("trois", false); // getting boolean

			/* exemple */
			/*
			String s = prefs.get(PREF_NAME, "a string"); // String
		    boolean b = prefs.getBoolean(PREF_NAME, true); // boolean
		    int i = prefs.getInt(PREF_NAME, 123); // int
		    long l = prefs.getLong(PREF_NAME, 123L); // long
		    float f = prefs.getFloat(PREF_NAME, 12.3F); // float
		    double d = prefs.getDouble(PREF_NAME, 12.3); // double 
			*/
			
			
			/* SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
			 
		     String sDefault = "Hello!";
		      String sStringFromPrefFile = settings.getString("myString", sDefault); // new text  or default Hello!
		 
		      int nDefaultIndex = 2; //
		      int nIndexFromPrefFile = settings.getInt("myInt", nDefaultIndex); // 4 or default 2
		 
		      Boolean bDefault = false;
		      Boolean bFromPrefFile = settings.getBoolean("silentMode", bDefault); // true or default false
		 */

			//Cursor curseur = createCursor();
			
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(
					this, 
					R.layout.row, 
					createCursor(), 
					new String[]{ DB_alarm.COL_NAME , DB_alarm.COL_DATETIME, DB_alarm.COL_DATETIME, DB_alarm.COL_DATETIME, DB_alarm.COL_DATETIME }, 
					new int[]{R.id.msg_tv, R.id.year_tv, R.id.month_tv, R.id.date_tv, R.id.time_tv}, 0);
			
			//reset variables
			/*
			record_id.clear(); 
			record_name.clear();
			record_from_date.clear(); 
			record_to_date.clear(); 
			record_datetime.clear();
			record_status.clear(); 
			record_created_time.clear(); 
			record_modified_time.clear(); 
			record_created_at.clear(); */
			
			ArrayList<String> un = new ArrayList<String>();
			ArrayList<String> deux = new ArrayList<String>();
			ArrayList<String> trois = new ArrayList<String>();
			/*
			if (curseur.moveToFirst()) 
			{
				do 
				{
					//get data from field 
					record_id.add(curseur.getString(curseur.getColumnIndex(DB_alarm.KEY_ID )));
					record_name.add(curseur.getString(curseur.getColumnIndex(DB_alarm.COL_NAME )));
					record_from_date.add(curseur.getString(curseur.getColumnIndex(DB_alarm.COL_FROMDATE ))); 
					record_to_date.add(curseur.getString(curseur.getColumnIndex(DB_alarm.COL_TODATE ))); 
					record_datetime.add(curseur.getString(curseur.getColumnIndex(DB_alarm.COL_DATETIME )));
					record_status.add(curseur.getString(curseur.getColumnIndex(DB_alarm.COL_STATUS ))); 
					record_created_time.add(curseur.getString(curseur.getColumnIndex(DB_alarm.COL_CREATEDTIME ))); 
					record_modified_time.add(curseur.getString(curseur.getColumnIndex(DB_alarm.COL_MODIFIEDTIME ))); 
					record_created_at.add(curseur.getString(curseur.getColumnIndex(DB_alarm.KEY_CREATED_AT ))); 
				
				} while (curseur.moveToNext());
				
			}
			*/
			
			adapter.setViewBinder(new ViewBinder() 
			{
				public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
					if (view.getId() == R.id.msg_tv) return false;

					TextView tv = (TextView)view;
					long timestamp = cursor.getLong(columnIndex);
					//dt.setTime(timestamp);
					
					Calendar cal_tmp = Calendar.getInstance();
					cal_tmp.setTimeInMillis(timestamp);
					Date dt = cal_tmp.getTime();
					
					int jour = cal_tmp.get(Calendar.DATE);
					String mois = monthArr[cal_tmp.get(Calendar.MONTH) +1 ];
					int annee = cal_tmp.get(Calendar.YEAR);
					
					switch(view.getId()) 
					{
							case R.id.year_tv:
								//tv.setText(String.valueOf(dt.getYear()+1900));
								tv.setText(String.valueOf(annee));
								break;
							case R.id.month_tv:
								//tv.setText(monthArr[dt.getMonth()+1]);
								tv.setText(mois);
								break;
							case R.id.date_tv:
								//tv.setText(String.valueOf(dt.getDate()));
								tv.setText(String.valueOf(jour));
								break;
							case R.id.time_tv:
								//long now = System.currentTimeMillis();
								//String txt = RemindMe.showRemainingTime() ? Util.getRemainingTime(time, now) : Util.getActualTime(dt.getHours(), dt.getMinutes());
								//if (TextUtils.isEmpty(txt)) txt = Util.getActualTime(dt.getHours(), dt.getMinutes());
								//tv.setText(txt);
								
								//RelativeLayout parent = (RelativeLayout)tv.getParent();
								//TextView tv2 = (TextView) parent.findViewById(R.id.msg_tv);
								//if (time < now) tv2.setTextColor(Color.parseColor("#555555"));
								//else tv2.setTextColor(Color.parseColor("#587498"));
								
								String option = "";
								
								Boolean option_alarme = Tools.showRemainingTime();
								
								// delai avant l'alarme
								if(option_alarme)
								{
									long now = System.currentTimeMillis();
									String delai = Tools.getRemainingTime(timestamp, now); 
									option = delai;
								}
								
								// heure de l'alarme
								if(!option_alarme)
								{
									//String heure_alarme = Tools.getActualTime(cal.get(Calendar.HOUR), cal.get(Calendar.MINUTE));
									
									int heure_format24h = cal_tmp.get(Calendar.HOUR_OF_DAY);
									// pas utile  int heure_format12h = cal_tmp.get(Calendar.HOUR);
									int minute = cal_tmp.get(Calendar.MINUTE);
									
									/*  format pour afficher les minutes */
									String str_minute = "";
									if(minute == 0) 
									{
									    str_minute = "00";
									}
									if(minute <= 9)
									{
									    str_minute = "0"  + Integer.toString(minute);
									}
									else
									{
										str_minute =  Integer.toString(minute);
									}
									
									/*  format pour afficher les minutes */
									String str_heure = "";
									if(heure_format24h == 0) 
									{
										str_heure = "00";
									}
									if(heure_format24h <= 9)
									{
										str_heure = "0"  + Integer.toString(heure_format24h);
									}
									else
									{
										str_heure =  Integer.toString(heure_format24h);
									}
									
									option = str_heure +" : " + str_minute;
								}
								
								
								tv.setText(option);
								
								break;
					}
					return true;
				}
			});
			
			setListAdapter(adapter);
			
			rangeText.setText(getRangeStr());
					
		}
		
		
		
		/*******************/
		
		@Override
		protected void onListItemClick(ListView l, View v, int position, long id)
		{
			//openContextMenu(v);
			
			 Intent intent = new Intent(MainActivity.this, debug.class);
			 intent.putExtra(EXTRA_POSITION, String.valueOf(position));
			 intent.putExtra(EXTRA_ID, String.valueOf(id));
			 startActivity(intent);
			 
			
			
		}
		
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
		{
			if (v.getId() == android.R.id.list) 
			{
				getMenuInflater().inflate(R.menu.context_menu, menu);
				menu.setHeaderTitle("Choose an Option");
				menu.setHeaderIcon(R.drawable.ic_dialog_menu_generic);
				
				AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
				//alarmMsg.setId(info.id);
				//alarmMsg.load(db);
				//if (alarmMsg.getDateTime() < System.currentTimeMillis()) 
				//	menu.removeItem(R.id.menu_edit);
			}
		}
		
		@Override
		public boolean onContextItemSelected(MenuItem item) 
		{
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
			boolean refresh = false;
			
			switch (item.getItemId())
			{
					case R.id.menu_edit:
						//alarmMsg.setId(info.id);
						//alarmMsg.load(db);
						//alarm.reset();
						//alarm.setId(alarmMsg.getAlarmId());
						//alarm.load(db);
						//showDialog(R.id.menu_edit);
						
						startActivity(new Intent(this, debug.class));
						
						break;
						
					case R.id.menu_delete:
						//dbHelper.cancelNotification(info.id, false);
						refresh = true;
						//Intent cancelThis = new Intent(this, AlarmService.class);
						//cancelThis.putExtra(AlarmMsg.COL_ID, String.valueOf(info.id));
						//cancelThis.setAction(AlarmService.CANCEL);
						//startService(cancelThis);
						Toast.makeText(getApplicationContext(), "Simple", Toast.LENGTH_LONG).show();
						break;
						
					case R.id.menu_delete_repeating:
						//alarmMsg.setId(info.id);
						//alarmMsg.load(db);
						//RemindMe.dbHelper.cancelNotification(db, alarmMsg.getAlarmId(), true);
						refresh = true;
						
						//Intent cancelRepeating = new Intent(this, AlarmService.class);
						//cancelRepeating.putExtra(AlarmMsg.COL_ALARMID, String.valueOf(alarmMsg.getAlarmId()));
						//cancelRepeating.setAction(AlarmService.CANCEL);
						//startService(cancelRepeating);
						Toast.makeText(getApplicationContext(), "Repeating", Toast.LENGTH_LONG).show();
						break;
			}
			
			// pour la mise à jour de la listview
			if (refresh)
			{
				SimpleCursorAdapter adapter = (SimpleCursorAdapter) getListAdapter();
		    	adapter.getCursor().requery();
		    	adapter.notifyDataSetChanged();
			}
			
			return true;
		}
		
		@Override
		protected void onPrepareDialog(int id, Dialog dialog) 
		{
			super.onPrepareDialog(id, dialog);
			switch (id)
			{
				case R.id.menu_edit:
					EditText msgEdit = (EditText) dialog.findViewById(R.id.msg_et);
					CheckBox soundCb = (CheckBox) dialog.findViewById(R.id.sound_cb);
					
					//msgEdit.setText(id_alarm.getName());
					//soundCb.setChecked(id_alarm.getSound());
					break;
			}
		}	
		
		@Override
		protected Dialog onCreateDialog(int id) 
		{
			switch (id) 
			{
					case R.id.menu_edit:
						return new AlertDialog.Builder(this)
						   .setTitle("Edit")
						   .setView(getLayoutInflater().inflate(R.layout.edit, null))
					       .setCancelable(false)
					       					       				       
					       .setPositiveButton("Ok", new DialogInterface.OnClickListener()
					       {
						           public void onClick(DialogInterface dialog, int id) 
						           {
							        	   Dialog d = (Dialog) dialog;
							        	   EditText msgEdit = (EditText) d.findViewById(R.id.msg_et);
							        	   CheckBox soundCb = (CheckBox) d.findViewById(R.id.sound_cb);
							        	   
							        	   //id_alarm.setSound(soundCb.isChecked());
							        	   if (!TextUtils.isEmpty(msgEdit.getText())) 
							        	   {
											   //id_alarm.setName(msgEdit.getText().toString());
											   //dbHelper.update(id_alarm );
												 

//											   dbHelper.save_alarm(id_alarm); 
											   //alarm.persist(db);
								        	   
							        		   // pour la mise à jour de la listview
											   SimpleCursorAdapter adapter = (SimpleCursorAdapter) getListAdapter();
											   adapter.getCursor().requery();
											   adapter.notifyDataSetChanged();
								        	   
							        	   }
							        	   else
							        	   {
							        		   Toast.makeText(MainActivity.this, "Enter a message", Toast.LENGTH_SHORT).show();
							        	   }
						           }
					       })
					       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
					       {
					           public void onClick(DialogInterface dialog, int id)
					           {
					                dialog.cancel();
					           }
					       })
					       .create();
			}
			return super.onCreateDialog(id);
		}
		
		
		/*******************/
		
		private String getRangeStr()
		{
				int date = cal.get(Calendar.DATE);
				int month = cal.get(Calendar.MONTH);
				int year = cal.get(Calendar.YEAR);
				dt.setTime(System.currentTimeMillis());
				
				switch(Tools.getDateRange()) 
				{
				//Calendar.get(Calendar.YEAR)
				
					case 0: // Daily
						if (date==dt.getDate() && month==dt.getMonth() && year==dt.getYear()+1900) 
						{	return "Today";
						
						}
						else
						{	
							return date + " " + monthArr[month+1] + " " + year ;
						}	
						
					case 1: // Weekly
						
						 
						 String aaa = monthArr[month+1];
						 String bbb =  move(+1);
						 int ccc = cal.get(Calendar.DATE);
						 String ddd = monthArr[cal.get(Calendar.MONTH)+1];
						 String eee	= move(-1); 
						String fff = date + " " + monthArr[month+1] + move(+1) + " - " + cal.get(Calendar.DATE) + " " + monthArr[cal.get(Calendar.MONTH)+1] + move(-1) + " " + year;
						return date + " " + monthArr[month+1] + move(+1) + " - " + cal.get(Calendar.DATE) + " " + monthArr[cal.get(Calendar.MONTH)+1] + move(-1) + " " + year;
						
					case 2: // Monthly
						return monthArr[month+1]+" " + year;
						
					case 3: // Yearly
						return year+"";
				}
				return null;
		}
		
		/*******************/
		
		public void onClick(View v) 
		{
			switch (v.getId())
			{
				case R.id.imageButton1:
					
					SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
//		    		SharedPreferences.Editor editor = settings.edit();
		    		// sauvegarde la selection 	
			    	//	SharedPreferences.Editor editor = settings.edit();
			    		// sauvegarde la selection 	
			    	String zorro = sp.getString(DATE_RANGE, null);
			    	Toast.makeText(getBaseContext(), zorro ,Toast.LENGTH_SHORT).show();
		    		
		    	//	SettingsActivity.retourne();
		    		
		    		//Preference pref = findPreference(SettingsActivity.DATE_RANGE);
		    		//SettingsActivity.findPreference("pref_key");
		    		
		    		
		    		//Preference pref = findPreference("DATE_RANGE");
		    		//CharSequence etat = pref.getSummary();
		    		//editor.putString("DATE_RANGE_CHANGE", etat.toString());
		    		//editor.commit();
					
					startActivity(new Intent(this, SettingsActivity.class));
//					Intent i = new Intent(this, debug.class);
//					startActivityForResult(i, 2);
					break;		
				case R.id.imageButton2:
					startActivity(new Intent(this, AddAlarm.class));
					break;
				case R.id.imageButton3:
					move(-1);
					rangeText.setText(getRangeStr());
					((SimpleCursorAdapter)getListAdapter()).changeCursor(createCursor());
					break;
				case R.id.imageButton4:
					move(+1);
					rangeText.setText(getRangeStr());
					((SimpleCursorAdapter)getListAdapter()).changeCursor(createCursor());
					break;			
			}
		}
/*		
		@Override  
	       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
	       {  
			 super.onActivityResult(requestCode, resultCode, data);  
             // check if the request code is same as what is passed  here it is 2  
              if(requestCode==2)  
                    {  
                       String message=data.getStringExtra("MESSAGE");   
                       Toast.makeText(getBaseContext(), message ,Toast.LENGTH_SHORT).show();
                       
                    }  
*/			
			/*
			 if(data != null && data.hasExtra("valeur_retour"))
			  {
					  String fichier = data.getExtras().getString("valeur_retour");
		          
		      			Toast.makeText(getBaseContext(), fichier ,Toast.LENGTH_SHORT).show();
		      		
			  }
			*/
/*	     }  
		
		/*protected void onActivityResult(int requestCode, int resultCode, Intent data)
		{
		if(resultCode==RESULT_OK && requestCode==1){
		Bundle MBuddle = data.getExtras();
		String MMessage = MBuddle .getString("Date");
		}
		}
*/
		
		
}