package com.androidbegin.buttonclicktutorial;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


// source Appli_alarm01 du 15 Décembre 2016

public class MainActivity extends Activity
{
		public static final String PREFERENCES_NAME = "MyPrefsFile";
		public static SharedPreferences sp;
	
		private ImageView previousButton, nextButton;
	    private static TextView currentDate;
	    private GridView calendarGridView;
	    private Button addEventButton, viewAgendaButton;
	     
	    private int MAX_CALENDAR_COLUMN = 42;
	    private SimpleDateFormat formatter = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
	    private Calendar cal = Calendar.getInstance(Locale.ENGLISH);
	    Map<String, String> dictionnaire = new HashMap<String, String>();
	    int shift_day_begin, shift_day_end;
	
     	List<Long> list_appointment; // = new ArrayList<Date>();
     
     	//	private GridviewAdapter mAdapter;
     
     	private GridviewAdapterbis mAdapterbis;
     
     
     	private ArrayList<String> listJours;
     	private LayoutInflater mInflater;

//     	private Context context;
     
     	List<Date> copy_dayValueInCells = new ArrayList<Date>();

 		DB_alarm db;
 		private SQLiteDatabase dataBase;

		int backposition = -1;
		int flag_ferie =  -1;

		final static ArrayList<appointment> appointment_DB = new ArrayList<appointment>();
		
		ArrayList<Long> timestamp_feries = new ArrayList<Long>();
		List<Date> datesFeries = new ArrayList<Date>();

		
		String COLOR_FERIE = "#15baa9";


		
		@Override
		public void onCreate(Bundle savedInstanceState)
		{
				super.onCreate(savedInstanceState);
				//setContentView(R.layout.activity_custom_calendar);
		
				// preferences
				PreferenceManager.setDefaultValues(this, R.xml.settings, false);
				sp = PreferenceManager.getDefaultSharedPreferences(this);
			
				db = new DB_alarm(getApplicationContext());
				
/*				
				List<Date> datesFeries = new ArrayList<Date>();
				datesFeries = Calendrier.getJourFeries(2017);
				for(int x = 0; x < datesFeries.size() ; x = x + 1) 
				{
					Date dt =  datesFeries.get(x);
			        Calendar dateCal = Calendar.getInstance();
					//Date mDate = monthlyDates.get(position);
					dateCal.setTime(dt);
		            long timestamp = dateCal.getTimeInMillis();
		            timestamp_feries.add(timestamp);	
				}
*/				
				
				//AlarmService.chargement_debug();
				
				////////////////////////////////////////debug();
				
			 	initializeUILayout();
			 	setupCalendar();
			 	
			 	setPreviousButtonClickEvent();
		        setNextButtonClickEvent();
		        setGridCellClickEvents();
		        
		        AddEventButtonClickEvent();
		        ViewAgendaButtonClickEvent();
		        
		        addEventButton.setEnabled(false);
		        viewAgendaButton.setEnabled(false);
	
				
	            //CalendarCustomView mView = (CalendarCustomView)findViewById(R.id.custom_calendar);
		}
	
		@Override
	    protected void onResume()
	    {
	            super.onResume();
	            //Toast.makeText(MainActivity.this, "Resume " , Toast.LENGTH_LONG).show();
				//appointment_DB.clear();
				//base();
		        addEventButton.setEnabled(false);
		        viewAgendaButton.setEnabled(false);
			 	setupCalendar();
	    }
	
		public LinearLayout createLayout(int iOrientation)
		{
				LinearLayout lay = new LinearLayout(this);		
				lay.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
				lay.setOrientation(iOrientation);
				return lay;
		}
	
		private void initializeUILayout()
		{
				LinearLayout layMain = createLayout(LinearLayout.VERTICAL);  	
		 		//layMain.setPadding(8, 8, 8, 8);
			 
		       	View view = getLayoutInflater().inflate(R.layout.activity_main, null);
		        
		        previousButton = (ImageView)view.findViewById(R.id.previous_month);
		        nextButton = (ImageView)view.findViewById(R.id.next_month);
		        currentDate = (TextView)view.findViewById(R.id.display_current_date);
		        addEventButton = (Button)view.findViewById(R.id.add_calendar_event);
		        calendarGridView = (GridView)view.findViewById(R.id.calendar_grid);
		        viewAgendaButton = (Button)view.findViewById(R.id.viewAgendaButton);
		        
		        layMain.addView(view);
		        setContentView(layMain);
		}
	
		 private void setPreviousButtonClickEvent()
		 {
		        previousButton.setOnClickListener(new OnClickListener()
		        {
		            @Override
		            public void onClick(View v) 
		            {
		                addEventButton.setEnabled(false);
		                viewAgendaButton.setEnabled(false);
		                cal.add(Calendar.MONTH, -1);
		                setupCalendar();
		            }
		        });
		 }
		    
		 private void setNextButtonClickEvent()
		 {
		        nextButton.setOnClickListener(new OnClickListener()
		        {
		            @Override
		            public void onClick(View v) 
		            {
		                addEventButton.setEnabled(false);
		                viewAgendaButton.setEnabled(false);
		                cal.add(Calendar.MONTH, 1);
		                setupCalendar();
		            }
		        });
		 }

	 
		private void AddEventButtonClickEvent()
		{
		    	addEventButton.setOnClickListener(new OnClickListener()
		        {
		    		  @Override
		              public void onClick(View v)
		              {
			              	String pos = String.valueOf(backposition);
			              	Date dt = copy_dayValueInCells.get(backposition);
			              	SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy ");
			              	String date_event = df.format(dt);
			              	//Toast.makeText(MainActivity.this, "Add Event " + pos + "  " + date_event , Toast.LENGTH_LONG).show();
			  				Intent intent = new Intent(MainActivity.this, AddEvent05.class);
			  				intent.putExtra("EXTRA", date_event);
			  				startActivity(intent);
		              }
		        });
		}

	    
	 	private void ViewAgendaButtonClickEvent()
	 	{
			 	viewAgendaButton.setOnClickListener(new OnClickListener()
		        {
		    		  @Override
		              public void onClick(View v)
		              {
		                	String pos = String.valueOf(backposition);
		                  	Date dt = copy_dayValueInCells.get(backposition);
		                  	SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy ");
		                  	String date_event = df.format(dt);
		                  	//Toast.makeText(MainActivity.this, "View agenda " + pos + "  " + date_event , Toast.LENGTH_LONG).show();
		    				Intent intent = new Intent(MainActivity.this, agenda02.class);
		    				intent.putExtra("EXTRA", date_event);
		    				startActivity(intent);
		              }
	
		        });
	 	}
	 
	  	private void setGridCellClickEvents()
	    {
	        calendarGridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
	        {
	            @Override
	            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
	            {
	                //Toast.makeText(context, "Clicked " + position, Toast.LENGTH_LONG).show();
	            	
	                addEventButton.setEnabled(true);
	                viewAgendaButton.setEnabled(true);
	                
	                
	                // detecter si la date est passée
/*	                int year = cal.get(Calendar.YEAR);	
	                int month = cal.get(Calendar.MONTH);	
	                int day = cal.get(Calendar.DAY_OF_MONTH);	

	                Calendar cal_date = Calendar.getInstance();
					cal_date.set(Calendar.YEAR, year);
					cal_date.set(Calendar.MONTH, month);
					cal_date.set(Calendar.DAY_OF_MONTH, day);
					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);
			        long timestamp_today = cal_date.getTimeInMillis();
*/	              	
			        
			        Date dt = copy_dayValueInCells.get(position);
	              	SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy");
	              	String date_event = df.format(dt);
	              	String[]tmp = date_event.split(" ");
				    int jour = Integer.parseInt(tmp[0]);
				    int mois = Integer.parseInt(tmp[1]);
				    int annee = Integer.parseInt(tmp[2]);
				    mois = mois - 1;
	                Calendar cal_date = Calendar.getInstance();
	                cal_date.set(annee, mois, jour, 0, 0, 0); 
					cal_date.set(Calendar.MILLISECOND, 0);
		            long timestamp_selection = cal_date.getTimeInMillis();
	              	
	                // long timestamp_selection = dt.getTime();
	              	
	              	Calendar c = Calendar.getInstance();
	              	c.set(Calendar.HOUR_OF_DAY, 0);
					c.set(Calendar.MINUTE, 0);
					c.set(Calendar.SECOND, 0);
					c.set(Calendar.MILLISECOND, 0);
					long timestamp_today = c.getTimeInMillis();
	              	
			        
					
					
	              	//SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	                //String formattedDate = dateformat.format(c.getTime());
	                

/*	              	
	              	Calendar cal_actif = Calendar.getInstance();
	              	String[]tmp = date_event.split(" ");
				    int jour = Integer.parseInt(tmp[0]);
				    int mois = Integer.parseInt(tmp[1]);
				    int annee = Integer.parseInt(tmp[2]);
				    mois = mois - 1;
					cal_actif.set(annee, mois, jour, 0, 0, 0); 
					cal_actif.set(Calendar.MILLISECOND, 0);
			        long timestamp_selection = cal_actif.getTimeInMillis();
*/			        
	              	//Toast.makeText(MainActivity.this, date_event, Toast.LENGTH_LONG).show();
	              	//long aqw = timestamp_selection - timestamp_today;

					
//		non actif depuis le 20 mars 2017			
	              	if(timestamp_selection < timestamp_today)
	              	{
	              		addEventButton.setEnabled(false);
	              	}
	              	
	              	else
	              	{	
	              		addEventButton.setEnabled(true);
	              	}
	                
	              	
	                String selectedItem = parent.getItemAtPosition(position).toString();
	                
	                //String col = "#ff5733"; orange
	                if (backposition != -1)
	                {
	                	if(backposition < shift_day_begin || backposition > shift_day_end  )
	                	{
	                		calendarGridView.getChildAt(backposition).setBackgroundColor(Color.parseColor("#cccccc"));  // gris 
	                		calendarGridView.getChildAt(position).setBackgroundColor(Color.parseColor("#18A608"));  // vert
	                		
	                		if(flag_ferie == 1)
	                		{
		                		calendarGridView.getChildAt(backposition).setBackgroundColor(Color.parseColor(COLOR_FERIE));  // gris 
		                		//calendarGridView.getChildAt(position).setBackgroundColor(Color.parseColor("#18A608"));  // vert
	                		}
	                		
	                	}
	                	else
	                	{	
	                		calendarGridView.getChildAt(backposition).setBackgroundColor(Color.parseColor("#ebeef0")); // ff5733  blanc
	                		calendarGridView.getChildAt(position).setBackgroundColor(Color.parseColor("#18A608"));  // vert
	                		
	                		
	                		if(flag_ferie == 1)
	                		{
		                		calendarGridView.getChildAt(backposition).setBackgroundColor(Color.parseColor(COLOR_FERIE));  // #444081
		                		//calendarGridView.getChildAt(position).setBackgroundColor(Color.parseColor("#18A608"));  // vert
	                		}
	                		 
	                	}	
	                }
	                else
	                {	
	                	calendarGridView.getChildAt(position).setBackgroundColor(Color.parseColor("#18A608"));  // vert
	                }
	                backposition = position;
	                

					boolean check_ferie = timestamp_feries.contains(timestamp_selection);
					if(check_ferie == true)
					{
						flag_ferie = 1;
					}
					else
					{
						flag_ferie = -1;
					}

	                
	                
	            }
	        });
	        
	        calendarGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
	        {

		       	 @Override
		       	 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
		       	 {
		       		SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy "); 
		       		String date_event = "";
		       		
		       		// appui long sans selection : par défaut on utilise la date du jour
		       		if(backposition == -1)
	            	{
	            		Date dt = new Date(); 
	            		date_event = df.format(dt);
	            		
	            	}
	            	else
	            	{
	            		String pos = String.valueOf(backposition);
	            		Date dt = copy_dayValueInCells.get(backposition);
	            		date_event = df.format(dt);
	            	}
		       		 
		       		 
		       		Toast.makeText(MainActivity.this, "Appui long"  , Toast.LENGTH_LONG).show();
	                	
	            	//Toast.makeText(context, "Affiche agenda " + pos + "  " + date_event , Toast.LENGTH_LONG).show();
	                
					//Intent intent = new Intent(context, agenda02.class);
					//intent.putExtra("EXTRA", date_event);
					//context.startActivity(intent);
					return true;
		       	 }
	       	 
	       	 });
	    
	    }
	    
	  	
	  	public  void base()
	    {
		        String requete = "SELECT * FROM table_appointment ORDER BY _id ASC" ;
				Cursor Cursor = db.DB_query(requete);
				int val = Cursor.getCount();
			    Log.i("************", String.valueOf(val));
		        
		        if(Cursor.moveToFirst())
		        {
		            do
		            {
		            			
	 							String sid = Cursor.getString(Cursor.getColumnIndex(DB_alarm.KEY_ID ));
		 						String titre = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_TITRE ));
		 						String start_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_START_TIME ));
		 						String end_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_END_TIME ));
		 						String phone = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_PHONE ));
		 						String ggnotes = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_NOTES ));
		 						
		 						String status = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_STATUS ));
		 						String creation = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_CREATEDTIME ));
		 						String modification = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_MODIFIEDTIME ));
		 						
		 						Date date_start = new Date(Long.parseLong(start_timestamp));
		 						Date date_end = new Date(Long.parseLong(end_timestamp));

		 						
		 						int id = Integer.valueOf(sid);
		 						appointment_DB.add(new appointment(id, titre, date_start, date_end, phone, ggnotes));
		 						
		            } 
		            while (Cursor.moveToNext());
		        }
		        
		     
		       int stop = 5;
		       stop = stop + 1;
	    }

	    
	    public  List<Long> getAllsAppointment(long min, long max)
	    {

		    	List<Long> list = new ArrayList<Long>(); 
		        
		        String requete = "SELECT * FROM table_appointment WHERE date >= " + min + " AND date <= " + max + " ORDER BY date ASC" ;
				Cursor Cursor = db.DB_query(requete);
				int val = Cursor.getCount();
			    Log.i("************", String.valueOf(val));
		        
		        if(Cursor.moveToFirst())
		        {
		            do
		            {
		            			String stimestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_DATE ));
		            			list.add(Long.parseLong(stimestamp));
		            } 
		            while (Cursor.moveToNext());
		        }
		        
		        return list;
		       
	    }
	 
	    protected void setupCalendar()
	    {
		        List<Date> dayValueInCells = new ArrayList<Date>();
		        
		        Calendar mCal = (Calendar)cal.clone();
		        mCal.set(Calendar.DAY_OF_MONTH, 1);
		        int firstDayOfTheMonth = mCal.get(Calendar.DAY_OF_WEEK) - 1;
		        mCal.add(Calendar.DAY_OF_MONTH, -firstDayOfTheMonth);
		        
		        while(dayValueInCells.size() < MAX_CALENDAR_COLUMN)
		        {
		            dayValueInCells.add(mCal.getTime());
		            mCal.add(Calendar.DAY_OF_MONTH, 1);
		        }
		        
		        Log.d("---->", "Number of date " + dayValueInCells.size());
		        String sDate = formatter.format(cal.getTime());
		                
		        String[] decoupe = sDate.split(" ");
		        dictionnaire.put("January", "0");
		        dictionnaire.put("February", "1");
		        dictionnaire.put("March", "2");
		        dictionnaire.put("April", "3");
		        dictionnaire.put("May", "4");
		        dictionnaire.put("June", "5");
		        dictionnaire.put("July", "6");
		        dictionnaire.put("August", "7");
		        dictionnaire.put("September", "8");
		        dictionnaire.put("October", "9");
		        dictionnaire.put("November", "10");
		        dictionnaire.put("December", "11");
	
		        String month = dictionnaire.get(decoupe[0]);
		        String year = decoupe[1];
		        
		        /**************************/
		        
		        timestamp_feries.clear();
		        
		        int annee = Integer.parseInt(year);
		        int annee_precedente = annee - 1; 
		        int annee_suivante = annee + 1; 
		        
		        datesFeries.clear();
				datesFeries = Calendrier.getJourFeries( annee_precedente );
				for(int x = 0; x < datesFeries.size() ; x = x + 1) 
				{
					Date dt =  datesFeries.get(x);
			        Calendar dateCal = Calendar.getInstance();
					//Date mDate = monthlyDates.get(position);
					dateCal.setTime(dt);
		            long timestamp = dateCal.getTimeInMillis();
		            timestamp_feries.add(timestamp);	
				}
		        
		        datesFeries.clear();
				datesFeries = Calendrier.getJourFeries( annee );
				for(int x = 0; x < datesFeries.size() ; x = x + 1) 
				{
					Date dt =  datesFeries.get(x);
			        Calendar dateCal = Calendar.getInstance();
					//Date mDate = monthlyDates.get(position);
					dateCal.setTime(dt);
		            long timestamp = dateCal.getTimeInMillis();
		            timestamp_feries.add(timestamp);	
				}
				
		        datesFeries.clear();
				datesFeries = Calendrier.getJourFeries( annee_suivante );
				for(int x = 0; x < datesFeries.size() ; x = x + 1) 
				{
					Date dt =  datesFeries.get(x);
			        Calendar dateCal = Calendar.getInstance();
					//Date mDate = monthlyDates.get(position);
					dateCal.setTime(dt);
		            long timestamp = dateCal.getTimeInMillis();
		            timestamp_feries.add(timestamp);	
				}
				
				
		        /*************************/
		        
		        Calendar calendar = Calendar.getInstance();
		        calendar.set(Calendar.YEAR,  Integer.parseInt(year) );
		        calendar.set(Calendar.MONTH,  Integer.parseInt(month) );
		        calendar.set(Calendar.DAY_OF_MONTH,1 );
		        calendar.set(Calendar.HOUR_OF_DAY,0 );
		        calendar.set(Calendar.MINUTE, 0);
		        calendar.set(Calendar.SECOND, 0);
		        calendar.set(Calendar.MILLISECOND, 0);
		        
	
		        Calendar cal1 = (Calendar) calendar.clone();
		        Calendar cal2 = (Calendar) calendar.clone();
		        Calendar cal3 = (Calendar) calendar.clone();
		        Calendar cal4 = (Calendar) calendar.clone();
		        
		        int numDays = calendar.getActualMaximum(Calendar.DATE);
		        
		        // premier jour du mois
		        SimpleDateFormat format_date = new SimpleDateFormat("dd MM yyyy");     
		        Date mois_premier_jour = calendar.getTime();             
		        String mois_premier_jour_string = format_date.format(mois_premier_jour);  
		        
		        // dernier jour du mois
		        int lastDate = cal3.getActualMaximum(cal3.DATE);
		        cal3.set(Calendar.DATE, lastDate);
		        int lastDay = cal3.get(Calendar.DAY_OF_WEEK);
		        Date mois_dernier_jour = cal3.getTime();             
		        String mois_dernier_jour_string = format_date.format(mois_dernier_jour);           
	
		        // premier jour matrice
		        shift_day_begin = firstDayOfTheMonth;
		        cal1.add(cal1.DATE, -shift_day_begin);  
		        long timestamp_start = cal1.getTimeInMillis();
		        Date premier_jour_matrice = cal1.getTime();             
		        String premier_jour_matrice_string = format_date.format(premier_jour_matrice);           
		        
		        // dernier jour matrice
		        shift_day_end = numDays + shift_day_begin - 1 ;
		        int zzz = 41 + 1 - numDays - shift_day_begin;  
		        cal3.add(cal3.DATE, zzz);
		        long timestamp_end = cal3.getTimeInMillis();
	
		        Date dernier_jour_matrice = cal3.getTime();             
		        String dernier_jour_matrice_string = format_date.format(dernier_jour_matrice);           
		        
		        list_appointment = null;
		        list_appointment = getAllsAppointment(timestamp_start, timestamp_end );
	
		        
		        // mAdapter = new GridAdapter(context, dayValueInCells, cal, mEvents);
		       // mAdapter = new GridAdapter(context, dayValueInCells, cal, list_appointment);
		       //		        calendarGridView.setAdapter(mAdapter);
		        //    mAdapterbis = new GridviewAdapterbis(this, dayValueInCells, cal);
		   //     gridView = (GridView) findViewById(R.id.calendar_grid);
		  //      gridView.setAdapter(mAdapterbis);
		     //   this.context = context;
		        
		        mAdapterbis = new GridviewAdapterbis(this, dayValueInCells, cal, list_appointment);
		        calendarGridView.setAdapter(mAdapterbis);
		        
		        String concat =  mois_premier_jour_string + "  " + mois_dernier_jour_string;
		        concat =  premier_jour_matrice_string + "  " + sDate + "  " + dernier_jour_matrice_string;
		        
		        copy_dayValueInCells = dayValueInCells;
		        
		        //currentDate.setText(concat);
		        currentDate.setText(sDate);

	    }
	
	  
	    private class GridviewAdapterbis extends ArrayAdapter 
	    {
		      //private static final String TAG = GridAdapter.class.getSimpleName();
		      private LayoutInflater mInflater;
		      private List<Date> monthlyDates;
		      private Calendar currentDate;
		      private List<Long> allEvents;
	      
		      public GridviewAdapterbis(Context context, List<Date> monthlyDates, Calendar currentDate, List<Long> allEvents ) 
		      {
		          super(context, R.layout.single_cell_layout);
		          this.monthlyDates = monthlyDates;
		          this.currentDate = currentDate;
		          this.allEvents = allEvents;
		          mInflater = LayoutInflater.from(context);
		      }
	      
		      @Override
		      public View getView(int position, View convertView, ViewGroup parent) 
		      {
	      	
			          Date mDate = monthlyDates.get(position);
			          Calendar dateCal = Calendar.getInstance();
			          dateCal.setTime(mDate);
			          int dayValue = dateCal.get(Calendar.DAY_OF_MONTH);
			          int displayMonth = dateCal.get(Calendar.MONTH) + 1;
			          int displayYear = dateCal.get(Calendar.YEAR);
			          int currentMonth = currentDate.get(Calendar.MONTH) + 1;
			          int currentYear = currentDate.get(Calendar.YEAR);
			          View view = convertView;
			          
			          if(view == null)
			          {
			              view = mInflater.inflate(R.layout.single_cell_layout, parent, false);
			          }
			          
			          if(displayMonth == currentMonth && displayYear == currentYear)
			          {
			          	
			              view.setBackgroundColor(Color.parseColor("#ebeef0")); // FF5733
			          }
			          else
			          {
			              view.setBackgroundColor(Color.parseColor("#cccccc"));
			          }
	          
			          //Add day to calendar
			          TextView cellNumber = (TextView)view.findViewById(R.id.calendar_date_id);
			          cellNumber.setText(String.valueOf(dayValue));
			          //Add events to the calendar
			          TextView eventIndicator = (TextView)view.findViewById(R.id.event_id);
			          Calendar eventCalendar = Calendar.getInstance();
	          
			          for(int i = 0; i < allEvents.size(); i++)
			          {
				          	long timestamp = allEvents.get(i);
				          	eventCalendar.setTimeInMillis(timestamp);
				          	if(dayValue == eventCalendar.get(Calendar.DAY_OF_MONTH) && displayMonth == eventCalendar.get(Calendar.MONTH) + 1 && displayYear == eventCalendar.get(Calendar.YEAR))
				          	{
				                  eventIndicator.setBackgroundColor(Color.parseColor("#FF4081"));
				          	}
			          }

			          for(int j = 0; j < timestamp_feries.size(); j++)
			          {
				          	long timestamp = timestamp_feries.get(j);
				          	eventCalendar.setTimeInMillis(timestamp);
				          	if(dayValue == eventCalendar.get(Calendar.DAY_OF_MONTH) && displayMonth == eventCalendar.get(Calendar.MONTH) + 1 && displayYear == eventCalendar.get(Calendar.YEAR))
				          	{
				                  //eventIndicator.setBackgroundColor(Color.parseColor("#444081"));
					              view.setBackgroundColor(Color.parseColor(COLOR_FERIE)); // FF5733  #444081
				          	}
			          }
	          
			          return view;
		      }
	      
		      @Override
		      public int getCount() 
		      {
		          return monthlyDates.size();
		      }
		      
		      //@Nullable
		      @Override
		      public Object getItem(int position) 
		      {
		          return monthlyDates.get(position);
		      }
		      
		      @Override
		      public int getPosition(Object item)
		      {
		          return monthlyDates.indexOf(item);
		      }
	    }
	
	

		@Override
		public boolean onCreateOptionsMenu(Menu menu)
		{
			getMenuInflater().inflate(R.menu.activity_main, menu);
			return true;
		}
	
	
		@Override
		public boolean onOptionsItemSelected(MenuItem item)
		{
		      switch (item.getItemId())
		      {
/*		      
		      		case R.id.add_event:
		      			Toast.makeText(getApplicationContext(),"Add event",Toast.LENGTH_SHORT).show();
		      			Intent Intent02 = new Intent(MainActivity.this, agenda02.class);
		      			startActivity(Intent02);
		      			return true;
			     
		      		case R.id.menu_help:
		      			Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
		      			Intent Intent01 = new Intent(MainActivity.this, agenda02.class);
		      			startActivity(Intent01);
		      			return true;
			      
		      		case R.id.menu_settings:
			          // Comportement du bouton "Paramètres"
			          return true;
*/			      
			          
			          
		      		case R.id.menu_remind:
		      			//Toast.makeText(getApplicationContext(),"Remind",Toast.LENGTH_SHORT).show();
		      			Intent Intent04 = new Intent(MainActivity.this, remind.class);
		      			startActivity(Intent04);
				        return true;
			        
		      		case R.id.menu_repeat:
		      			//Toast.makeText(getApplicationContext(),"Remind",Toast.LENGTH_SHORT).show();
		      			Intent Intent06 = new Intent(MainActivity.this, repeat_list.class);  // au lieu de vibrate et image_button01
		      			startActivity(Intent06);
				        return true;
			        
				        
				        
		      		case R.id.menu_about:
		      			//Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
		      			//Intent Intent03 = new Intent(MainActivity.this, repeat_list.class);
		      			//startActivity(Intent03);
		      			about();
				        return true;
	
		      		case R.id.menu_quit:
		      			//Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
		      			//Intent Intent03 = new Intent(MainActivity.this, datepicker.class);
		      			//startActivity(Intent03);
		      			finish();
				        return true;    
			          
		      		default:
			          return super.onOptionsItemSelected(item);
			 }
		}
		
		
		public void debug()
		{
		
		
		String sid , titre,  start_timestamp , end_timestamp , phone , notes , option_delai, delai, option_vibrate, option_ringtone , status ,	 creation,  modification; 
		
		//Intent i;
		//PendingIntent pi;				
		//AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Cursor c;
		
        String requete = "SELECT * FROM table_appointment ORDER BY _id ASC" ;
		Cursor Cursor = db.DB_query(requete);
		int val = Cursor.getCount();
	    Log.i("************", String.valueOf(val));
        Toast.makeText(getBaseContext(),  "BOOT sequence" , Toast.LENGTH_LONG).show();
        
        int cpt = 1;
        
        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 ));
 						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 ));
 						
 						long now = System.currentTimeMillis();
 						
 						long Idlongval = Long.valueOf(sid);
 						long Timelongval = Long.valueOf(start_timestamp);
 						long Delailongval = Long.valueOf(delai);
 						
						// prendre en compte le delai
						long time_millis = Timelongval - Delailongval;
						
 						if( now < Timelongval)
 						{
	 							//i = new Intent(this, AlarmReceiver.class);
	 							//i.putExtra("index", sid);
	 							//i.putExtra("titre", titre);
	 							//pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
	 							//am.set(AlarmManager.RTC_WAKEUP, startTime, pi);
	 							
	 	 						Intent i;
	 	 						PendingIntent pi;				
	 	 						AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
	 	 						
	 	 						i = new Intent(this, AlarmReceiver.class);
	 	 						long keycode = Idlongval; 
	 	 						i.putExtra("keycode", Idlongval);  // long
	 	 						i.putExtra("titre", titre);
	 	 						i.putExtra("time", time_millis);   // long
	 	 						i.putExtra("delai", Delailongval); // long
	 	 						i.putExtra("option_vibrate", option_vibrate);
	 	 						i.putExtra("option_ringtone", option_ringtone);
	 	 						
	 	 						pi = PendingIntent.getBroadcast(this, (int) keycode, i, PendingIntent.FLAG_UPDATE_CURRENT);
	 	 						am.set(AlarmManager.RTC_WAKEUP, time_millis, pi);
	 	 						
	 	 					    Log.i("***** LOADING *******", String.valueOf(cpt));
	 	 					    cpt = cpt + 1;
 						}
 						
/* 						
 						
 						Intent i;
 						PendingIntent pi;				
 						AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
 						
 						i = new Intent(this, AlarmReceiver.class);
 						long keycode = alarmId; 
 						i.putExtra("keycode", alarmId);
 						i.putExtra("titre", titre);
 						i.putExtra("time", time);
 						i.putExtra("delai", delai);
 						//i.putExtra("option_delai", option_delai);
 						i.putExtra("option_vibrate", option_vibrate);
 						i.putExtra("option_ringtone", option_ringtone);
 						
 						pi = PendingIntent.getBroadcast(this, (int) keycode, i, PendingIntent.FLAG_UPDATE_CURRENT);
 						//long now = System.currentTimeMillis();
 						//long time = now + 60 * 1000 * 2;
 						am.set(AlarmManager.RTC_WAKEUP, time, pi);
*/
 						
 						
 						
            } 
            while (Cursor.moveToNext());
        }

        
		    Log.i("***** FINISH LOADING *******", "dssdddd");


        Cursor.close();	

		
		}
		
		
		/******************************************/
		
		public void about()
		{
			
			//http://androidexample.com/Custom_Dialog_-_Android_Example/index.php?view=article_discription&aid=88
			
	        final Dialog dialog = new Dialog(MainActivity.this);
	        dialog.setContentView(R.layout.about01);
	        dialog.setTitle("About:");

//	        TextView text = (TextView) dialog.findViewById(R.id.textDialog);
//	        text.setText("Alarm application.");
//	        ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
//	        image.setImageResource(R.drawable.ic_launcher);

	        dialog.show();
	        
	        /*
	        Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
	        // if decline button is clicked, close the custom dialog
	        declineButton.setOnClickListener(new OnClickListener() 
	        {
	            @Override
	            public void onClick(View v) 
	            {
	                // Close dialog
	                dialog.dismiss();
	            }
	        });*/
	        
	        Button dialogCloseButton = (Button) dialog.findViewById(R.id.close_button);
	           dialogCloseButton.setOnClickListener(new OnClickListener(){
	              @Override
	              public void onClick(View v) {
	               // TODO Auto-generated method stub
	                  dialog.dismiss();
	              }                                                                             
	         });
			
		}
		

		
	
	
}