package com.example.appli_calendar06;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
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.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 com.example.appli_calendar06.DatabaseQuery;


public class CalendarCustomView extends LinearLayout
{
    private static final String TAG = CalendarCustomView.class.getSimpleName();
    private ImageView previousButton, nextButton;
    private TextView currentDate;
    private GridView calendarGridView;
    private Button addEventButton;
    private static final int MAX_CALENDAR_COLUMN = 42;
    private int month, year;
    private SimpleDateFormat formatter = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
    private SimpleDateFormat format = new SimpleDateFormat("MMMM", Locale.FRANCE);

    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> dayValueInCells = new ArrayList<Date>();
    
    
    int shift_day_begin, shift_day_end;
    String position_calendar;
    
    DB_calendar db;
    
    //private DatabaseQuery mQuery;
    
    public CalendarCustomView(Context context) 
    {
        super(context);
    }
    public CalendarCustomView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        this.context = context;
        
        db = new DB_calendar(context);
        
        initializeUILayout();
        setUpCalendarAdapter();
        setPreviousButtonClickEvent();
        setNextButtonClickEvent();
        setGridCellClickEvents();
        AddEventButtonClickEvent();
    }
    
    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);
    }
    
    private void setPreviousButtonClickEvent()
    {
        previousButton.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                cal.add(Calendar.MONTH, -1);
                setUpCalendarAdapter();
            }
        });
    }
    private void setNextButtonClickEvent()
    {
        nextButton.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                cal.add(Calendar.MONTH, 1);
                setUpCalendarAdapter();
            }
        });
    }
    
    private void AddEventButtonClickEvent()
    {
    	addEventButton.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //cal.add(Calendar.MONTH, -1);
                //setUpCalendarAdapter();
            	String pos = String.valueOf(backposition);
            	
            	Date dt = dayValueInCells.get(backposition);
            	SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy ");

            	String reportDate = df.format(dt);
            	
                Toast.makeText(context, "Add Event " + pos + "  " + reportDate , 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();
                String selectedItem = parent.getItemAtPosition(position).toString();
                
                //calendarGridView.getChildAt(position).getBackgroundColor();

                //calendarGridView.setBackgroundColor(125);
                String col = "#ff5733";
                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"));

                	}
                	else
                	{	
                		calendarGridView.getChildAt(backposition).setBackgroundColor(Color.parseColor("#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)
        	 {
        		 Toast.makeText(context, "LONG" + position, Toast.LENGTH_LONG).show();        	 
        	 return true;
        	 }
        	 
        	 });
        
       /* 
        calendarGridView.getOnItemLongClickListener();
        
        calendarGridView.setOnLongClickListener( new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View v, int pos, long id) {
                mPosition = pos;
                parent.showContextMenu();
                return true;
            }
        });
        /*
        calendarGridView.setOnItemLongClickListener(new OnItemLongClickListener()
        {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
            {
                // TODO Auto-generated method stub
                arg1.bringToFront();
                Toast.makeText(context, "" + "long press", Toast.LENGTH_SHORT) .show();    
                
                 
                return false;
            }});
         
        
        calendarGridView.setOnItemLongClickListener(new AdapterView.OnItemClickListener()
        
        private OnItemLongClickListener listener = new OnItemLongClickListener() {
         
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    Log.d(TAG, "OnItemLongClickListener");
                    choicedPosition = position;
                    showDialog(DIALOG_DELETE_ONE_WMICON);
                    return true;
                }
            };
        */
         
        
    }
    private void setUpCalendarAdapter()
    {
        //List<Date> dayValueInCells = new ArrayList<Date>();
        //mQuery = new DatabaseQuery(context);
        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) );
        int numDays = calendar.getActualMaximum(Calendar.DATE);

        shift_day_begin = firstDayOfTheMonth;
        shift_day_end = numDays + shift_day_begin - 1 ;
*/        
    }
}