package org.arkiwi.app.adapter;

import java.util.ArrayList;

import org.arkiwi.app.utility.IconContextMenuItem;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.TextView;

/**
 * Menu-like list adapter with icon
 */
public class AdapterIconMenu extends BaseAdapter {
	private static final int LIST_PREFERED_HEIGHT = 65;
	@SuppressWarnings("unused")
	private final static String LOG_TAG = "IconMenuAdapter";
	private Context context = null;
    private ArrayList<IconContextMenuItem> mItems = new ArrayList<IconContextMenuItem>();
	
    public AdapterIconMenu(Context context) {
    	this.context = context;
    }
    
    /**
     * add item to adapter
     * @param menuItem
     */
    public void addItem(IconContextMenuItem menuItem) {
    	mItems.add(menuItem);
    }
    
	@Override
	public int getCount() {
		return mItems.size();
	}

	@Override
	public Object getItem(int position) {
		return mItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		IconContextMenuItem item = (IconContextMenuItem) getItem(position);
		return item.actionTag;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		IconContextMenuItem item = (IconContextMenuItem) getItem(position);
		
		Resources res = context.getResources();
		
		if (convertView == null) {
        	TextView temp = new TextView(context);
        	AbsListView.LayoutParams param = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, 
        																  AbsListView.LayoutParams.WRAP_CONTENT);
        	temp.setLayoutParams(param);
        	temp.setPadding((int)toPixel(res, 15), 0, (int)toPixel(res, 15), 0);
        	temp.setGravity(android.view.Gravity.CENTER_VERTICAL);
        	
        	Theme th = context.getTheme();
			TypedValue tv = new TypedValue();
			
			if (th.resolveAttribute(android.R.attr.textAppearanceLargeInverse, tv, true)) {
				temp.setTextAppearance(context, tv.resourceId);
			}
        	
        	temp.setMinHeight(LIST_PREFERED_HEIGHT);
        	temp.setCompoundDrawablePadding((int)toPixel(res, 14));
        	convertView = temp;
		}
		
		TextView textView = (TextView) convertView;
		textView.setTag(item);
		textView.setText(item.text);
		textView.setCompoundDrawablesWithIntrinsicBounds(item.image, null, null, null);
    	
        return textView;
	}
	
	private float toPixel(Resources res, int dip) {
		float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, res.getDisplayMetrics());
		return px;
	}
}