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.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
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.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.io.FileWriter;


//import com.example.db01.Alarm;
//import com.example.db01.AlarmMsg;


public class MainActivity extends ListActivity
{
		private DbAdapter dbHelper;
		private SimpleCursorAdapter dataAdapter;
		public final Calendar cal = Calendar.getInstance();
		private int range = 3;
		public final Date dt = new Date();
		private String[] monthArr;
		private TextView rangeText;
		public static SharedPreferences sp;
		
	//	private AlarmMsg alarmMsg = new AlarmMsg();
		
		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";
		
		Alarm id_alarm = new Alarm();
		AlarmMsg id_alarmMsg = new AlarmMsg();
		

		@Override
		public void onCreate(Bundle savedInstanceState)
		{
			 	super.onCreate(savedInstanceState);
			 	setContentView(R.layout.activity_main);
				
			 	dbHelper = new DbAdapter(this);
			 	dbHelper.open();
			 	
			 	findViews();
			 	
				PreferenceManager.setDefaultValues(this, R.xml.settings, false);
				sp = PreferenceManager.getDefaultSharedPreferences(this);
			 	
			 	monthArr = getResources().getStringArray(R.array.spinner3_arr);
			 	
			 	int r = getDateRange();
				switch(r)
				{
					case 3: // Yearly
						cal.set(Calendar.MONTH, 0);
						
					case 2: // Monthly
						cal.set(Calendar.DATE, 1);
						
					case 1: // Weekly
						if (range==1) cal.set(Calendar.DATE, cal.getFirstDayOfWeek());
						
					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);
				}
			 	
			 	
			 	Date dt = new Date();
			 	String time = "1482700200000";
				long lg = Long.parseLong(time);
				dt.setTime(lg);
			 	
			
			 	
//			 	createAlarm("alarm1", 3, 9 , 2016, 21, 20 ); 
/*			 	
			 	Alarm id_alarm = new Alarm();
			 	id_alarm.setName("nom");
			 	id_alarm.setFromDate("un");
			 	id_alarm.setToDate("deux");
			 	id_alarm.setRule("trois");
			 	id_alarm.setInterval("quatre");
			 	id_alarm.setSound(false);
			 	dbHelper.addAlarm(id_alarm);
			 	
*/			
			 	
			 	registerForContextMenu(getListView());
				
			 	
		}
		
		private void findViews() 
		{
			rangeText = (TextView) findViewById(R.id.range_tv);
		}

		
		public void createAlarm(String name, int day, int month, int year , int hour, int min ) 
		{
				  String fromDate = Utils.getDateStr(year, month+1, day);
				  String toDate = Utils.getTimeStr(hour, min);
			
				  Alarm alarm = new Alarm();
				  AlarmTime alarmTime = new AlarmTime();
				  long alarmId = 0;
				 
				  
				  Calendar calendar = Calendar.getInstance();
				  calendar.set(2016, 9, 3,  23, 10, 0);
				  long startTime = calendar.getTimeInMillis();
				  
				  Date dt = new Date();
				  
				  
				  String time = "1475609700000";
				  long lg = Long.parseLong(time);
				  
				  dt.setTime(startTime);
				  
				  long now = System.currentTimeMillis();
				  alarm.setName(name );
				  alarm.setFromDate( fromDate );
				  alarm.setToDate("Null");
				  alarm.setRule("Null");
				  alarm.setInterval("Null");
				  alarm.setSound(true);
				  alarmId = dbHelper.addAlarm(alarm);
				  alarmTime.setAt(toDate);
				  alarmTime.setAlarmId(alarmId);
				 // dbHelper.addAlarmTime(alarmTime);
				  
		}
		
		private String move(int step) 
		{
			switch(getDateRange())
			{
				case 0:
					cal.add(Calendar.DATE, 1*step);
					break;		
				case 1:
					cal.add(Calendar.DATE, 7*step);
					break;
				case 2:
					cal.add(Calendar.MONTH, 1*step);
					break;
				case 3:
					cal.add(Calendar.YEAR, 1*step);
					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());
			
		}
		
		/*******************/
		
		@Override
		protected void onListItemClick(ListView l, View v, int position, long id)
		{
			openContextMenu(v);
			//Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
		}
		
		@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;
				//long coco = info.id;
				//alarmMsg.setId(info.id);

				AlarmMsg alarmMsgId = new AlarmMsg();
				alarmMsgId = dbHelper.load_msg(info.id);
				if (alarmMsgId.getDateTime() < System.currentTimeMillis()) 
				{	
					menu.removeItem(R.id.menu_edit);
				}
				/*else
				{
					Toast.makeText(getApplicationContext(), "TRACE", Toast.LENGTH_LONG).show();
				}*/
					
					
			}
		}
		
		@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);
						
						id_alarmMsg.setId(info.id);
						id_alarmMsg  = dbHelper.load_msg(info.id);
						id_alarm.reset();
						id_alarm.setId(id_alarmMsg.getAlarmId());
						id_alarm = dbHelper.load_alarm(id_alarmMsg.getAlarmId()); 
						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);
						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 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(getDateRange())  
			{
				case 0: // Daily
					if (date==dt.getDate() && month==dt.getMonth() && year==dt.getYear()+1900) return "Today";
					else return date+" "+monthArr[month+1];
					
				case 1: // Weekly
					return date+" "+monthArr[month+1] + move(+1) + " - " + cal.get(Calendar.DATE)+" "+monthArr[cal.get(Calendar.MONTH)+1] + move(-1);
					
				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:
					startActivity(new Intent(this, SettingsActivity.class));
					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;			
			}
		}

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

		public static int getDateRange()
		{
			return Integer.parseInt(sp.getString(DATE_RANGE, "0"));
		}
		
		public static String getDateFormat()
		{
			return sp.getString(DATE_FORMAT, DEFAULT_DATE_FORMAT);
		}	
		
		public static boolean is24Hours() 
		{
			return sp.getBoolean(TIME_FORMAT, true);
		}
		
		public static boolean isVibrate()
		{
			return sp.getBoolean(VIBRATE_PREF, true);
		}
		
		public static String getRingtone() 
		{
			return sp.getString(RINGTONE_PREF, android.provider.Settings.System.DEFAULT_NOTIFICATION_URI.toString());
		}

		
}