package com.example.preferences02;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

public class debug_alarm_listing extends ListActivity //AppCompatActivity
{

 	//DatabaseHelper db;
 	ListView mListView;
 	SimpleCursorAdapter dataAdapter;
	TextView rangeText;
	ListView userList;
  
	public final Calendar cal = Calendar.getInstance();
	public final Date dt = new Date();
	String[] monthArr = new String[]{ "Month","Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"  };
  
	public static SharedPreferences sp;
  
	
	//variables to store records
	private ArrayList<String> record_id = new ArrayList<String>();
	private ArrayList<String> record_name = new ArrayList<String>();
	private ArrayList<String> record_from_date = new ArrayList<String>();
	private ArrayList<String> record_to_date = new ArrayList<String>();
	private ArrayList<String> record_datetime = new ArrayList<String>();
	private ArrayList<String> record_status = new ArrayList<String>();
	private ArrayList<String> record_created_time = new ArrayList<String>();
	private ArrayList<String> record_modified_time = new ArrayList<String>();
	private ArrayList<String> record_created_at = new ArrayList<String>();
	
	
	DB_alarm db;
	private SQLiteDatabase dataBase;
	
	//private AlertDialog.Builder build;
	
	private AlertDialog disclaimer;
	
	 public void onCreate(Bundle savedInstanceState)
	 {
	        super.onCreate(savedInstanceState);
	        //setContentView(R.layout.view_debug_alarm_listing);
	        setContentView(R.layout.acceuil);
	        db = new DB_alarm(getApplicationContext());
	        
	    	PreferenceManager.setDefaultValues(this, R.xml.parametres, false);
			sp = PreferenceManager.getDefaultSharedPreferences(this);
			
			rangeText = (TextView) findViewById(R.id.range_tv);
	        
			//userList = (ListView) findViewById(R.id.list_view);

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

//		 	 registerForContextMenu(getListView());
		 	
			//click to update data
			/*
			userList.setOnItemClickListener(new OnItemClickListener() 
			{
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
				{
					//Intent i = new Intent(getApplicationContext(),	ViewRecord.class);
					//i.putExtra("stafid", stafid.get(arg2));
					//startActivity(i);
					
					Toast.makeText(getApplicationContext(), "Gloup", Toast.LENGTH_LONG).show();
					
				}
			});//end setOnItemClickListener
			*/
			
			
			
			/*userList.setOnItemLongClickListener(new OnItemLongClickListener() {
			     public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
			              //.....
			              // Example, Display Toast of Position
			              Toast.makeText(getApplicationContext(), " " + position , Toast.LENGTH_LONG).show();
			              // Other Example action items:
			              // Remove Selected Item from ListView
			             return true;
			    }
			}); */
			
	        
	 }      
	 
	 @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"));
		}
/***************************************************************************/	 
		
		
		
	/* @Override
	 protected void onListItemClick(ListView l, View v, int position, long id)
	 {
			openContextMenu(v);
		    //Toast.makeText(getApplicationContext(), "Item in position " + position + " clicked" + id, Toast.LENGTH_LONG).show();
			
			//invoking AlertDialog box
			//build = new AlertDialog.Builder(DisplayList.this);
			//build.setTitle("Update/Delete staff " + nama.get(arg2));
			//build.setMessage("Do you want to update/delete the record?(Hit back to cancel)");
			
	 }*/

		 
		
		

	 
/***************************************************************************/	 
	 
	 
	/*
	 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long rowId)
	 {
	     Log.i("Chimee", "Long click working");
	     return false;
	 }
	/* 
	 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) 
	 {
	        Toast.makeText(getApplicationContext(), "Item in position " + position + " clicked", Toast.LENGTH_LONG).show();
	        // Return true to consume the click event. In this case the
	        // onListItemClick listener is not called anymore.
	        return true;
	        
	        //  android:longClickable="true"
	      
	   
	  }
	 
	/* 
	 @Override
		protected void onListItemClick(ListView l, View v, int position, long id)
		{
			//openContextMenu(v);
			 Toast.makeText(getApplicationContext(), String.valueOf(id) , Toast.LENGTH_LONG).show();
			 Intent intent = new Intent(MainActivity.this, display_alarm.class); 
			 intent.putExtra("position", position);
			 intent.putExtra("id", id);
			 startActivity(intent);
			 
			  db.delete_alarm(id);
			 
			
		}
	*/ 
	 
	 
	 
	 
	 public void onClick(View v) 
		{
			switch (v.getId())
			{
				case R.id.imageButton1:
					//startActivity(new Intent(this, Settings.class));
					startActivity(new Intent(this, parametres_activity.class));
					
					break;		
//				case R.id.imageButton2:
//					startActivity(new Intent(this, AddAlarm.class));
//					break;
				case R.id.imageButton3:
					move(-1);
					rangeText.setText(getRangeStr());
					//displayData();
					((SimpleCursorAdapter)getListAdapter()).changeCursor(createCursor());
					break;
				case R.id.imageButton4:
					move(+1);
					rangeText.setText(getRangeStr());
					//displayData();
					((SimpleCursorAdapter)getListAdapter()).changeCursor(createCursor());
					break;	
							
			}
		}
	 
	 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
					break;
				case 3:
					cal.add(Calendar.YEAR, 1*step); // année
					break;			
			}
			return "";
		}    
		
		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
						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;
		}
		

/******************************
	 @Override
	 protected void onResume() 
	 {
			//refresh data for screen is invoked/displayed
			displayData();
			//Toast.makeText(getApplicationContext(), "TAP to view complete info, \n LONG-TAP to update/delete...", Toast.LENGTH_LONG).show();
			super.onResume();
			//rangeText.setText(getRangeStr());
	 }
/********************************/	 
		
		private Cursor createCursor()
		{
			dataBase = db.getWritableDatabase();	
			 
	 		long temps_actuel = 0;
	 		temps_actuel = 	cal.getTimeInMillis();
	 		String max = cal.getTimeInMillis() + move(+1);
	 		String min = cal.getTimeInMillis() + move(-1);
			
			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();

			//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());
					
		}
	 
	 
	 private void displayData() 
		{
		 
		 		dataBase = db.getWritableDatabase();	
		 
		 		long temps_actuel = 0;
		 		temps_actuel = 	cal.getTimeInMillis();
		 		String max = cal.getTimeInMillis() + move(+1);
		 		String min = cal.getTimeInMillis() + move(-1);
		 
				//the SQL command to fetched all records from the table
				//Cursor mCursor = dataBase.rawQuery("SELECT * FROM "	+ DB_alarm.TABLE, null);
				
				
				String requete = "SELECT * FROM table_alarm WHERE datetime >= " + max + " AND datetime <= " + min ;
				Cursor mCursor = db.DB_query(requete);
				int val = mCursor .getCount();
				String TAG = " ****************** ";
   			    Log.i(TAG, String.valueOf(val));
				
				
				//the SQL command to fetched all records from the table
				//Cursor mCursor = dataBase.rawQuery("SELECT * FROM "	+ DB_alarm.TABLE, null);
		
				//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>();
				
				/*
				un.add("a");
				un.add("b");
				un.add("c");
				
				deux.add("aaaa");
				deux.add("bbbb");
				deux.add("cccc");
				
				trois.add("123");
				trois.add("456");
				trois.add("789");
				*/
				
				//fetch each record
				
				if (mCursor.moveToFirst()) 
				{
					do 
					{
						//get data from field 
						record_id.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.KEY_ID )));
						record_name.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.COL_NAME )));
						record_from_date.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.COL_FROMDATE ))); 
						record_to_date.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.COL_TODATE ))); 
						record_datetime.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.COL_DATETIME )));
						record_status.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.COL_STATUS ))); 
						record_created_time.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.COL_CREATEDTIME ))); 
						record_modified_time.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.COL_MODIFIEDTIME ))); 
						record_created_at.add(mCursor.getString(mCursor.getColumnIndex(DB_alarm.KEY_CREATED_AT ))); 
						
						//nama.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.NAMA)));
						//jbt.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.JBT)));
						
					} while (mCursor.moveToNext());
					
				}
				
				//display to screen
				//Listing_alarm_adapter disadpt = new Listing_alarm_adapter(debug_alarm_listing.this, un, deux, trois);
				
				Listing_alarm_adapter disadpt = new Listing_alarm_adapter(debug_alarm_listing.this, record_id, record_name, record_datetime);
				setListAdapter(disadpt);
				rangeText.setText(getRangeStr());
				
				//userList.setAdapter(disadpt);
				
				mCursor.close();
		}//end displayData
	 
	 /*******************************************************************************/
	 
	 @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);
						break;
						
					case R.id.menu_delete:
						//RemindMe.dbHelper.cancelNotification(db, 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);
						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);
						break;
			}
			
			if (refresh) 
			{
				SimpleCursorAdapter adapter = (SimpleCursorAdapter) getListAdapter();
		    	adapter.getCursor().requery();
		    	adapter.notifyDataSetChanged();
			}
			
			return true;
		}

		@Override
		protected void onListItemClick(ListView l, View v, int position, long id) 
		{
			openContextMenu(v);
		} 
	
	 
		@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);
			        	   
			        	   //alarm.setSound(soundCb.isChecked());
			        	   if (!TextUtils.isEmpty(msgEdit.getText())) 
			        	   {
								//alarm.setName(msgEdit.getText().toString());
								//alarm.persist(db);
				        	   
								SimpleCursorAdapter adapter = (SimpleCursorAdapter) getListAdapter();
								adapter.getCursor().requery();
								adapter.notifyDataSetChanged();
				        	   
			        	   } 
			        	   else 
			        	   {
			        		   Toast.makeText(debug_alarm_listing.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);
		}

		
		@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(alarm.getName());
				//soundCb.setChecked(alarm.getSound());
				break;
			}
		}	

		
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			getMenuInflater().inflate(R.menu.options_menu, menu);
	        return true;
		}
		
		@Override
		public boolean onPrepareOptionsMenu(Menu menu) {
	        if (getListAdapter().isEmpty()) {
	        	menu.findItem(R.id.menu_delete_all).setEnabled(false);
	        } else {
	        	menu.findItem(R.id.menu_delete_all).setEnabled(true);
	        }
			return true;
		}	

		
		@Override
		public boolean onOptionsItemSelected(MenuItem item) 
		{
			switch (item.getItemId()) {
			case R.id.menu_delete_all:
				String startTime = cal.getTimeInMillis()+move(+1);
				String endTime = cal.getTimeInMillis()+move(-1);
				//RemindMe.dbHelper.cancelNotification(db, startTime, endTime);
				
				//Intent cancelAll = new Intent(this, AlarmService.class);
				//cancelAll.putExtra(Alarm.COL_FROMDATE, startTime);
				//cancelAll.putExtra(Alarm.COL_TODATE, endTime);
				//cancelAll.setAction(AlarmService.CANCEL);
				//startService(cancelAll);
				
				SimpleCursorAdapter adapter = (SimpleCursorAdapter) getListAdapter();
		    	adapter.getCursor().requery();
		    	adapter.notifyDataSetChanged();			
				return true;
			}		
			return super.onOptionsItemSelected(item);
		}

		@Override
		protected void onDestroy() 
		{
			if (disclaimer != null) 
				disclaimer.dismiss();
			super.onDestroy();
		}	

	 
	
}
