package com.androidbegin.buttonclicktutorial;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.ParseException;
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 java.util.Vector;


// https://inducesmile.com/android/how-to-create-android-custom-calendar-view-with-events/

public class CalendarCustomView extends LinearLayout
{

	private static final String TAG = CalendarCustomView.class.getSimpleName();
    private ImageView previousButton, nextButton;
    private static TextView currentDate;
    private GridView calendarGridView;
    private Button addEventButton, btn_agenda_view;
    private static final int MAX_CALENDAR_COLUMN = 42;
    private int month, year;
    private SimpleDateFormat formatter = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
    private Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    private Context context;
    private GridAdapter mAdapter;

    
    String selectedItem;
    TextView GridViewItems,BackSelectedItem;
    int backposition = -1;
    
    Map<String, String> dictionnaire = new HashMap<String, String>();
    
    List<Date> copy_dayValueInCells = new ArrayList<Date>();
    
    List<Long> list_appointment; // = new ArrayList<Date>();
    
    List<Date> tmp = new ArrayList<Date>();
    //List<Date> feries = new ArrayList<Date>();
    //List<List<Date>> dateList = new ArrayList<List<Date>>();
    
    int shift_day_begin, shift_day_end;
    String position_calendar;
    
    //DB_calendar db;
    static DB_alarm db;
    
    public CalendarCustomView(Context context) 
    {
        super(context);
    }
    
    public CalendarCustomView(Context context, AttributeSet attrs) 
    {
        super(context, attrs);
        this.context = context;
        
        //db = new DB_calendar(context);
        db = new DB_alarm(getContext());
        
        Vector tab_feries = new Vector();
        
        
        int annee [] = { 2016 , 2017, 2018,  2019, 2020};
        
        for( int i = 0; i< annee.length; ++i)
        {
        	tmp.clear();
        	tmp = Calendrier.getJourFeries(annee[i]); 
        	int taille = tmp.size();
        	for( int j = 0; j< taille; ++j)
        	{
        		Date dt = tmp.get(j);
        		long timestamp = dt.getTime();
        		tab_feries.add(timestamp);
        	}	
        	
        }
           
        
        initializeUILayout();
        setUpCalendarAdapter();
        setPreviousButtonClickEvent();
        setNextButtonClickEvent();
        setGridCellClickEvents();
        AddEventButtonClickEvent();
        btn_agenda_viewClickEvent();
        
        addEventButton.setEnabled(false);
        btn_agenda_view.setEnabled(false);
        

    }
    
  
    
    public CalendarCustomView(Context context, AttributeSet attrs, int defStyleAttr) 
    {
        super(context, attrs, defStyleAttr);
    }
    
    private void initializeUILayout()
    {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.calendar_layout, this);
        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);
        btn_agenda_view = (Button)view.findViewById(R.id.btn_agenda_view);
        
    }
    
    private void setPreviousButtonClickEvent()
    {
        previousButton.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) 
            {
                addEventButton.setEnabled(false);
                btn_agenda_view.setEnabled(false);
                cal.add(Calendar.MONTH, -1);
                setUpCalendarAdapter();
            }
        });
    }
    
    private void setNextButtonClickEvent()
    {
        nextButton.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) 
            {
                addEventButton.setEnabled(false);
                btn_agenda_view.setEnabled(false);
                cal.add(Calendar.MONTH, 1);
                setUpCalendarAdapter();
            }
        });
    }
    
    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(context, "+++++Add Event " + pos + "  " + date_event , Toast.LENGTH_LONG).show();
                  
  				//long id = info.id;
  				//int position = info.position;
  				Intent intent = new Intent(context, AddEvent02.class);
  				intent.putExtra("EXTRA", date_event);
  				
  				//intent.putExtra(EXTRA_POSITION, String.valueOf(position));
  				//intent.putExtra(EXTRA_ID, String.valueOf(id));
  				context.startActivity(intent);
  				
  				
  				//ntent intent=new Intent(MainActivity.this,SecondActivity.class);  
                //startActivityForResult(intent, 2);// Activity is started with requestCode 2  

  		         Toast.makeText(context, "Clicked " , Toast.LENGTH_LONG).show();

                  
              }

        });
    }

    
    
     
   /* protected void startActivityForResult(Intent intent, int i) 
    {
		// TODO Auto-generated method stub
		
	}*/
/*
	private void startActivityForResult(int requestCode, int resultCode, Intent data)  
    {  
              super.onActivityResult(requestCode, resultCode, data);  
               // check if the request code is same as what is passed  here it is 2  
                if(requestCode==2)  
                      {  
                         String message=data.getStringExtra("MESSAGE");   
                         textView1.setText(message);  
                      }  
  }  
	
*/	
    
    private void btn_agenda_viewClickEvent()
    {
    	btn_agenda_view.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);
    				Intent intent = new Intent(context, agenda02.class);
    				intent.putExtra("EXTRA", date_event);
    				context.startActivity(intent);
              }

        });
    }

	//@Override
    protected void onResume() 
  	{
    	 /*initializeUILayout();
         setUpCalendarAdapter();
         setPreviousButtonClickEvent();
         setNextButtonClickEvent();
         setGridCellClickEvents();
         AddEventButtonClickEvent();
         */
         Toast.makeText(context, "Clicked " , Toast.LENGTH_LONG).show();
         
  	}
    
    
    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);
                btn_agenda_view.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);
            	}
	       		 
	       		 
//	       		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(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 static List<Long> getAllsAppointment(long min, long max)
    {

        // List<EventObjects> events = new ArrayList<>();
    	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(TAG, 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 setUpCalendarAdapter()
    {
        List<Date> dayValueInCells = new ArrayList<Date>();
        //mQuery = new DatabaseQuery(context);
        //List<EventObjects> mEvents = mQuery.getAllFutureEvents();
        
       // List<EventObjects> mEvents = db.getAllFutureEvents();
        
        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(TAG, "Number of date " + dayValueInCells.size());
        String sDate = formatter.format(cal.getTime());
        
        //currentDate.setText(sDate);
        
       // mAdapter = new GridAdapter(context, dayValueInCells, cal, mEvents);
       // calendarGridView.setAdapter(mAdapter);
        
                
        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);           
     
        // 1483225200000
        // 1486767600000
        
        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);

        
        
        copy_dayValueInCells = new ArrayList<Date>();  
        
    	//String date1 = df.format(cal1);
    	//String date2 = df.format(cal2);
        
        //String aaa = String.valueOf(premier_jour_mois);
        //String concat = String.valueOf(zzz) + " " + String.valueOf(shift_day_begin) + " " + String.valueOf(shift_day_end) + " " + aaa + " " + month + " " + year ; 
        //currentDate.setText(concat);
       
        //concat = date1_string + " " + date2_string ; 
        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);

    }
    
    
    
     
}