package com.wasu.cs.widget;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import cn.com.wasu.main.R;

/**
 * 多列listview
 * 
 * @author zhangrm@wasu.com
 */
public class MusicMultiColumnList extends GridView implements
		android.widget.AdapterView.OnItemSelectedListener {

	private Context mContext;

	private int mColumns;

	public int getColumns() {
		return mColumns;
	}

	public void setColumns(int mColumns) {	
		this.mColumns = mColumns;
		setNumColumns(this.mColumns);
	}

	private int mHorizontalSpacing;
	/**
	 * 高亮的位置
	 */
	private int mHighlighted;
	private boolean mClearingFocus;

	public MusicMultiColumnList(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public MusicMultiColumnList(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public MusicMultiColumnList(Context context) {
		super(context);
		init(context);
	}

	private void init(Context context) {
		this.mContext = context;

		if (mContext == null) {
			return;
		}

		setContentDescription("内容信息列表");
		
		mHorizontalSpacing = mContext.getResources().getDimensionPixelSize(
				R.dimen.d_20dp);

		setFocusable(true);
		setFocusableInTouchMode(true);
		setClipToPadding(false);
		setCacheColorHint(0x00000000);
		setChildrenDrawingOrderEnabled(true);
		setNumColumns(mColumns);
		setSelector(R.drawable.leftnav_bar_item_background);
		setSoundEffectsEnabled(false);
		setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
		setHorizontalSpacing(mHorizontalSpacing);
		setOnItemSelectedListener(this);

		resetScrollBar();
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		
		if (getAdapter() != null) {
			int itemHeight = mContext.getResources().getDimensionPixelSize(R.dimen.d_71dp);
			if (getMeasuredHeight() < (getAdapter().getCount() * itemHeight) / mColumns) {
				setFastScrollAlwaysVisible(true);
			} else {
				setFastScrollAlwaysVisible(false);
			}
		}
	}

	/**
	 * 修改scrollbar样式
	 */
	@SuppressLint("NewApi")
	private void resetScrollBar() {
		try {
			Field mFastScroller = AbsListView.class.getDeclaredField("mFastScroller");
			mFastScroller.setAccessible(true);
			Object o = mFastScroller.get(this);
			if (Build.VERSION.SDK_INT < 19) { //4.4以下
				// 修改透明度
//				Field mScrollFade = mFastScroller.getType().getDeclaredField("mScrollFade");
//				mScrollFade.setAccessible(true);
//				Object scrollFadeObj = mScrollFade.get(o);
//				Class<?>[] classes = mScrollFade.getDeclaringClass().getDeclaredClasses();
//				for (Class<?> clazz : classes) {
//					if (clazz.getName().contains("ScrollFade")) {
//						Field alphaMax = clazz.getDeclaredField("ALPHA_MAX");
//						alphaMax.setAccessible(true);
//						alphaMax.set(scrollFadeObj, 0);
//					}
//				}
				// 滑动指示器
				Field mThumbDrawable = mFastScroller.getType().getDeclaredField("mThumbDrawable");
				mThumbDrawable.setAccessible(true);
				Drawable thumbDrawable = (Drawable) mThumbDrawable.get(o);
				thumbDrawable = getResources().getDrawable(R.drawable.scrollbar_drawable_vertical_thumb);
				mThumbDrawable.set(o, thumbDrawable);
				// 滑动指示器宽度
				Field mThumbWidth = mFastScroller.getType().getDeclaredField("mThumbW");
				mThumbWidth.setAccessible(true);
				int thumbWidth = (Integer) mThumbWidth.get(o);
				thumbWidth = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
				mThumbWidth.set(o, thumbWidth);
				//滑动指示器高度
				Field mThumbHeight = mFastScroller.getType().getDeclaredField("mThumbH");
				mThumbHeight.setAccessible(true);
				int thumbHeight = (Integer) mThumbHeight.get(o);
				thumbHeight = mContext.getResources().getDimensionPixelSize(R.dimen.d_90dp);;
				mThumbHeight.set(o, thumbHeight);
				// 背景
//				Field mTrackDrawable = mFastScroller.getType().getDeclaredField("mTrackDrawable");
//				mTrackDrawable.setAccessible(true);
//				Drawable trackDrawable = (Drawable) mTrackDrawable.get(o);
//				trackDrawable = getResources().getDrawable(R.drawable.scrollbar_vertical_track);
//				mTrackDrawable.set(o, trackDrawable);
			} else {
				// 滑动指示器
				Field mThumbImage = mFastScroller.getType().getDeclaredField("mThumbImage");
				mThumbImage.setAccessible(true);
				ImageView thumbImage = (ImageView) mThumbImage.get(o);
				thumbImage.setBackground(getResources().getDrawable(R.drawable.scrollbar_drawable_vertical_thumb));
				mThumbImage.set(o, thumbImage);
				// 背景
				Field mTrackImage = mFastScroller.getType().getDeclaredField("mTrackImage");
				mTrackImage.setAccessible(true);
				ImageView trackImage = (ImageView) mTrackImage.get(o);
				trackImage.setBackground(getResources().getDrawable(R.drawable.scrollbar_drawable_vertical_track));
				mTrackImage.set(o, trackImage);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setHighlighted(int index) {
		mHighlighted = index;
	}

	@Override
	public void addFocusables(ArrayList<View> views, int direction,
			int focusableMode) {
		int selectedIndex = mHighlighted - getFirstVisiblePosition();
		if (!hasFocus() && selectedIndex >= 0
				&& selectedIndex < getChildCount() && direction == FOCUS_RIGHT) {
			setSelection(mHighlighted);
			getChildAt(selectedIndex).addFocusables(views, direction,
					focusableMode);
		} else {
			super.addFocusables(views, direction, focusableMode);
		}
	}

	@Override
	public void clearFocus() {
		mClearingFocus = true;
		super.clearFocus();
		mClearingFocus = false;
	}

	@Override
	public void clearChildFocus(View child) {
		if (mClearingFocus) {
			super.clearChildFocus(child);
		} else {
			post(new Runnable() {
				public void run() {
					setSelection(mHighlighted);
				}
			});
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		setHighlighted(position);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (mHighlighted % mColumns == 0) {
			if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
				performItemClick(getSelectedView(), mHighlighted, getItemIdAtPosition(mHighlighted));
				return true;
			}
			if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
				return super.onKeyDown(keyCode, event);
			}
		}
		
		int count = getAdapter().getCount();
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			if (mHighlighted != 0) {
				setSelection(mHighlighted - 1);
				return true;
			}
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			if (mHighlighted != count - 1) {
				setSelection(mHighlighted + 1);
			}
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
			performItemClick(getSelectedView(), mHighlighted, getItemIdAtPosition(mHighlighted));
		}
		
		return super.onKeyDown(keyCode, event);
	}

}
