

package ru.filipenko.contactlens;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;


public class CalendarAdapter extends BaseAdapter implements OnClickListener, OnLongClickListener {

    public interface SelectionListener {
        public void onClick(int day, boolean isLongClick);
    }

    private LayoutInflater mInflater;
    private SelectionListener mSelectionListener;
    private final String[] mItems = new String[42];
    private Button mPressedButton = null;

    public CalendarAdapter(Context context,
                           SelectionListener selectionListener,
                           int daysInMonth,
                           int firstWeekDay) {
        mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mSelectionListener = selectionListener;

        for (int i = 0; i < daysInMonth; i++)
            mItems[firstWeekDay - 1 + i] = Integer.toString(i + 1);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.gridcell, parent, false);
        }
        Button button = (Button)convertView.findViewById(R.id.calendar_day_gridcell);
        TextView textView = (TextView)convertView.findViewById(R.id.num_events_per_day);

        button.setText(mItems[position]);
        button.setTag((Object)mItems[position]);
        button.setOnClickListener(this);
        button.setOnLongClickListener(this);

        return convertView;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public String getItem(int position) {
        return mItems[position];
    }

    @Override
    public int getCount() {
        return mItems.length;
    }

    @Override
    public void onClick(View view) {
        Button button = (Button)view;
        if (mPressedButton != button && button.getTag() != null) {
            mSelectionListener.onClick(Integer.parseInt((String)button.getTag()), false);
            if (mPressedButton != null)
                mPressedButton.setBackgroundResource(R.drawable.calendar_button_selector);
            button.setBackgroundResource(R.drawable.calendar_bg_orange);
            mPressedButton = button;
        }
    }

    @Override
    public boolean onLongClick(View view) {
        Button button = (Button)view;
        if (mPressedButton == button && button.getTag() != null) {
            mSelectionListener.onClick(Integer.parseInt((String)view.getTag()), true);
            return true;
        }
        return false;
    }

}
