package com.wasu.cs.widget;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.wasu.cs.widget.BlockLinearLayout;
import com.wasu.module.log.WLog;

import cn.com.wasu.main.R;

/**
 * @author jeepc
 * 历史收藏内容区
 */
public class HisFavListScrollView extends ScrollView implements OnClickListener {

	private Context mContext;
	/**
	 * Item点击的回调
	 */
	private OnItemClickListener mListener;

	private Adapter mAdapter;
	/**
	 * 屏幕的高度
	 */
	private int mScreenHeight;
	/**
	 * 每个条目的高度
	 */
	private int mItemHeight = getResources().getDimensionPixelOffset(R.dimen.d_303dp);
	private BlockLinearLayout mContainer;
	private LinearLayout mTimelineLayout;

	/**
	 * 条目总数
	 */
	private int mItemCount;

	private boolean flag = false;
	private final String TAG="ListScrollView";

	public HisFavListScrollView(Context context) {
		super(context);
		this.mContext = context;
		calWinHeight();
		initView();
	}

	public HisFavListScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mContext = context;
		calWinHeight();
		initView();
	}

	public HisFavListScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		this.mContext = context;
		calWinHeight();
		initView();
	}

	private void initView() {
		this.setVerticalScrollBarEnabled(false);
		View view = LayoutInflater.from(mContext).inflate(R.layout.his_fav_content_layout, this);
		mContainer = (BlockLinearLayout) view.findViewById(R.id.layoutBody);
		mContainer = (BlockLinearLayout) findViewById(R.id.layoutBody);
		mContainer.setOnFocusSearchListener(focusSearchListener);
		mTimelineLayout = (LinearLayout)view.findViewById(R.id.timeline_layout);
	}

	/**
	 * 焦点分发拦截控制
	 */
	private final BlockLinearLayout.OnFocusSearchListener focusSearchListener = new BlockLinearLayout.OnFocusSearchListener() {
		@Override
		public View onFocusSearch(View focused, int direction) {
			if (direction==FOCUS_LEFT || direction == View.FOCUS_RIGHT) {
				WLog.e("jeepc","-----------------"+direction);
				WLog.e("jeepc",focused==null?"null":focused.toString());
				return focused;
			}
			return null;
		}
	};

	//计算屏幕高度
	private void calWinHeight(){
		WindowManager wm = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		mScreenHeight = outMetrics.heightPixels;
		mScreenHeight -= getStatusHeight(mContext);
	}

	/**
	 * 适配器
	 * @author zhy
	 *
	 */
	public static abstract class Adapter {
		public abstract View getContainerView( int pos);
		public abstract View getTimelineView(int pos);

		public abstract int getCount();

	}

	/**
	 * 点击的回调
	 */
	public interface OnItemClickListener {
		void onItemClick(int pos, View view);
	}



	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//		notifyDataSetChanged();

		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}


	public void addChildView(View line,View view) {
		mTimelineLayout.addView(line);
		mContainer.addView(view);
	}

	/**
	 * 在容器末尾添加一个Item
	 * @param i
	 */
	private void addContainerView(int i) {
		View item = mAdapter.getContainerView(i);
		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT, mItemHeight);
		item.setLayoutParams(lp);//设置参数
		item.setTag(i);//设置Tag
		item.setOnClickListener(this);//添加事件
		mContainer.addView(item);
	}
	private void addTimelineView(int i) {
		View item = mAdapter.getTimelineView(i);
		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT, mItemHeight);
		item.setLayoutParams(lp);//设置参数
		item.setTag(i);//设置Tag
		item.setOnClickListener(this);//添加事件
		mTimelineLayout.addView(item);
	}

	/**
	 * 检查当前getScrollY,显示完成Item，或者收缩此Item
	 */
	private void checkForReset() {
		int val = getScrollY() % mItemHeight;
		if (val >= mItemHeight / 2) {
			smoothScrollTo(0, mItemHeight);
		} else {
			smoothScrollTo(0, 0);
		}

	}

	/**
	 * 获得状态栏的高度
	 *
	 * @param context
	 * @return
	 */
	public int getStatusHeight(Context context) {

		int statusHeight = -1;
		try {
			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height")
					.get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return statusHeight;
	}

	public void setAdapter(Adapter mAdapter) {
		WLog.d("danxx" ,"setAdapter");
		this.mAdapter = mAdapter;
		notifyDataSetChanged();
	}

	/**
	 * 设置item的高度  默认是280
	 * @param height
	 */
	public void setmItemHeight(int height){
		mItemHeight = height;
	}

	private void notifyDataSetChanged(){
		//防止多次调用
		if (!flag) {
			//根据Adapter的方法，为容器添加Item
			if (mAdapter != null) {
				mItemCount = mAdapter.getCount();
				mTimelineLayout.removeAllViews();
				mContainer.removeAllViews();
				for (int i = 0; i < mItemCount ; i++){
					addTimelineView(i);
					addContainerView(i);
				}
			}
		}
	}

	public void setOnItemClickListener(OnItemClickListener mListener)
	{
		this.mListener = mListener;
	}

	@Override
	public void onClick(View v) {
		int pos = (Integer) v.getTag();
		if (mListener != null) {
			mListener.onItemClick(pos, v);
		}
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		flag = true;
	}

	@Override
	protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
		if (getChildCount() == 0) return 0;

		int height = getHeight();
		int screenTop = getScrollY();
		int screenBottom = screenTop + height;
		/**增加提前滚动距离**/
		int fadingEdge = getVerticalFadingEdgeLength()+this.getResources().getDimensionPixelSize(
				R.dimen.d_200dp);

		// leave room for top fading edge as long as rect isn't at very top
		if (rect.top > 0) {
			screenTop += fadingEdge;
		}

		// leave room for bottom fading edge as long as rect isn't at very bottom
		if (rect.bottom < getChildAt(0).getHeight()) {
			screenBottom -= fadingEdge;
		}

		int scrollYDelta = 0;

		if (rect.bottom > screenBottom && rect.top > screenTop) {
			// need to move down to get it in view: move down just enough so
			// that the entire rectangle is in view (or at least the first
			// screen size chunk).

			if (rect.height() > height) {
				// just enough to get screen size chunk on
				scrollYDelta += (rect.top - screenTop);
			} else {
				// get entire rect at bottom of screen
				scrollYDelta += (rect.bottom - screenBottom);
			}

			// make sure we aren't scrolling beyond the end of our content
			int bottom = getChildAt(0).getBottom();
			int distanceToBottom = bottom - screenBottom;
			scrollYDelta = Math.min(scrollYDelta, distanceToBottom);

		} else if (rect.top < screenTop && rect.bottom < screenBottom) {
			// need to move up to get it in view: move up just enough so that
			// entire rectangle is in view (or at least the first screen
			// size chunk of it).

			if (rect.height() > height) {
				// screen size chunk
				scrollYDelta -= (screenBottom - rect.bottom);
			} else {
				// entire rect at top
				scrollYDelta -= (screenTop - rect.top);
			}

			// make sure we aren't scrolling any further than the top our content
			scrollYDelta = Math.max(scrollYDelta, -getScrollY());
		}
		return scrollYDelta;
	}
}
