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.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;

		final static ArrayList<appointment> appointment_DB = new ArrayList<appointment>();

		
		@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());
				
			 	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, AddEvent02.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);
	                
	                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"));
	                		calendarGridView.getChildAt(position).setBackgroundColor(Color.parseColor("#18A608"));  // vert
	                	}
	                	else
	                	{	
	                		calendarGridView.getChildAt(backposition).setBackgroundColor(Color.parseColor("#ebeef0")); // ff5733
	                		calendarGridView.getChildAt(position).setBackgroundColor(Color.parseColor("#18A608"));
	                	}	
	                }
	                else
	                {	
	                	calendarGridView.getChildAt(position).setBackgroundColor(Color.parseColor("#18A608"));
	                }
	                backposition = position;
	                
	            }
	        });
	        
	        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];
		        
		        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"));
				          	}
			          }

	          
			          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_gui:
		      			Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
		      			Intent Intent03 = new Intent(MainActivity.this, gui.class);
		      			startActivity(Intent03);
				        return true;
			        */  
			          
			          
		      		case R.id.menu_datepicker:
		      			//Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
		      			Intent Intent04 = new Intent(MainActivity.this, datepicker.class);
		      			startActivity(Intent04);
				        return true;
			          
		      		case R.id.menu_about:
		      			Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
		      			//Intent Intent03 = new Intent(MainActivity.this, datepicker.class);
		      			//startActivity(Intent03);
				        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);
			 }
		}
	
	
}