package com.wasu.cs.widget;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;

import cn.com.wasu.main.R;

/**
 * Created by chenming on 2016/11/4.
 *
 * @Description: 少儿频道首页中的tab控件
 * @email chenming@wasu.com
 */

public class HorentialFocusRecycleView extends RecyclerView {
	// self
	private HorentialFocusRecycleView mRecycleView;
	// context
	private Context mContext;
	// 布局管理器
	private LinearLayoutManager mLayoutManager;

	//栏目名称
	private String[] names;
	//栏目卡通头像对应的uri
	private String[] uris;
	// 记录当前的位置（0是初始位置）
	private int mViewPos = 0;
	// Adapter全局（用于刷新数据）
	private MyTabAdapter mMyTabAdapter;
	// 点击事件
	private OnItemClickListener itemClickListener;
	// 焦点变换事件
	private OnItemFocusChangeListener onItemFocusChangeListener;
	// item存在的布局文件
	private int mItemLayout;
	// 三个drawable三种样式
	private Drawable tabdefault, tabfocused, tabindicator;



	// leaveTag 失去焦点
	private ScrollView parentscroll;
	private View upFocusView;
	private View downFocusView;
	private boolean mLeaveTag = false;
	private int tabsCount = 0;
	private TranslateAnimation shakeAnim;
	/*private static final int[] picres = {R.drawable.spongebob, R.drawable.ggbond,
			R.drawable.verney, R.drawable.insect, R.drawable.beautifulgirl};*/
	// 获得焦点时设定item
	Handler handler = new android.os.Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				setItemFocus();
			}
		}
	};
	private int scrolldeltady;
	private final int bluetext = getResources().getColor(R.color.btn_bule_text);
	private final int whitetext = getResources().getColor(R.color.white);

	public HorentialFocusRecycleView(Context context) {
		super(context);
		mContext = context;
		mRecycleView = HorentialFocusRecycleView.this;
		init();
	}

	public HorentialFocusRecycleView(Context context, @Nullable AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		mRecycleView = HorentialFocusRecycleView.this;
		init();
	}

	public HorentialFocusRecycleView(Context context, @Nullable AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		mRecycleView = HorentialFocusRecycleView.this;
		init();
	}

	private void init() {
		scrolldeltady = getResources().getDimensionPixelOffset(R.dimen.d_230dp);
		mLayoutManager = new LinearLayoutManager(mContext);
		mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
		// 设定布局管理器
		mRecycleView.setLayoutManager(mLayoutManager);
		// 设置适配器
		mMyTabAdapter = new MyTabAdapter();
		mRecycleView.setAdapter(mMyTabAdapter);
		// 设置间隔
		mRecycleView.addItemDecoration(new ItemDecoration() {
			@Override
			public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
				super.getItemOffsets(outRect, view, parent, state);
				int spacingPixels = getResources().getDimensionPixelOffset(R.dimen.d_63dp);
				int position = parent.getChildPosition(view);
				if (position == 0) {  //最左边的item 左间距为0
					outRect.left = 0;
				} else if (position == tabsCount - 1) {
					outRect.left = spacingPixels;
					outRect.right = 0;
				} else {
					outRect.left = spacingPixels;
				}
			}
		});
		// 要求RecycleView先于子控件获得焦点
		mRecycleView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
		mRecycleView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if (hasFocus) {
					setItemFocus();
				}
			}
		});
	}

	public void setViewPos(int viewPos) {
		mViewPos = viewPos;
	}

	/**
	 * 必须调用这个setData
	 * SET后自动刷新
	 */
	public void setData(String[] names, String[] uris) {
		if (names != null && uris != null) {
			this.names = names;
			this.uris = uris;
		}
		mMyTabAdapter.notifyDataSetChanged();
	}

	public int getViewPos() {
		return mViewPos;
	}


	/**
	 * 设置布局和变化的三个文件
	 * <p>
	 * drawSelct0 -> item的默认样式
	 * drawSelct1 -> item被选中时带红框的样式
	 * drawSelct2 -> item选中后失去焦点的样式
	 */
	public void setLayoutAndDrawable(int itemLayout, Drawable drawSelct0, Drawable drawSelct1, Drawable drawSelct2) {
		mItemLayout = itemLayout;
		tabdefault = drawSelct0;
		tabfocused = drawSelct1;
		tabindicator = drawSelct2;
	}

	/**
	 * 初始化晃动动画实例
	 */
	private void initAnimation() {
		shakeAnim = new TranslateAnimation(0, 0, 4, -4);
		shakeAnim.setInterpolator(new OvershootInterpolator());
		shakeAnim.setDuration(100);
		shakeAnim.setRepeatCount(3);
		shakeAnim.setRepeatMode(Animation.REVERSE);
	}

	/**
	 * tab栏上下获取焦点的视图
	 *
	 * @param
	 */
	public void setUpFocusView(View upFocusView) {
		this.upFocusView = upFocusView;
	}

	public void setDownFocusView(View downFocusView) {
		this.downFocusView = downFocusView;
	}
	public void setParentscroll(ScrollView parentscroll) {
		this.parentscroll = parentscroll;
	}
	/**
	 * Recycleview之间focus失效，使用外部调用来识别失去焦点
	 */
	public void setLeaveTag() {
		mLeaveTag = true;
	}


	private class MyTabAdapter extends RecyclerView.Adapter<MyTabAdapter.MyViewHolder> {

		@Override
		public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			MyViewHolder holder = new MyViewHolder(LayoutInflater.from(mContext).inflate(mItemLayout, parent, false));
			return holder;
		}

		@Override
		public void onBindViewHolder(final MyViewHolder holder, final int position) {
			tabsCount = getItemCount();
			holder.textview.setText(names[position]);
			if (uris != null) {
				FrescoImageFetcherModule.getInstance().attachImage(uris[position], holder.cartoonimage);
			}
			holder.itemView.setFocusable(true);

			// 焦点变换监听
			View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
				@Override
				public void onFocusChange(View view, boolean hasFoucs) {
					if (mLeaveTag) {
						mLeaveTag = false;
						setItemFocus();
						return;
					}
					mLeaveTag = false;
					if (hasFoucs) {
						setDefult();
						// 刷新位置
						mViewPos = holder.getLayoutPosition();
						setHasFocus();
					} else {
						mViewPos = holder.getLayoutPosition();
						setLeaveFocus();
					}
				}
			};
			holder.itemView.setOnFocusChangeListener(onFocusChangeListener);

			// 添加点击事件
			if (itemClickListener != null) {
				holder.itemView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						itemClickListener.onItemClick(position, names[position]);

					}
				});
			}
			//对触屏设备添加触摸事件监听
			holder.itemView.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						return v.requestFocus();
					}
					return false;
				}
			});
			//对按键焦点进行控制
			holder.itemView.setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() == KeyEvent.ACTION_DOWN) {
						parentscroll.fullScroll(ScrollView.FOCUS_DOWN);
						downFocusView.requestFocus();
						return true;
					} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP && event.getAction() == KeyEvent.ACTION_DOWN) {
						parentscroll.fullScroll(ScrollView.FOCUS_UP);
						upFocusView.requestFocus();
						return true;
					} else if (position == tabsCount - 1 && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
							&& event.getAction() == KeyEvent.ACTION_DOWN) {
						mRecycleView.getItemView(0).requestFocus();
						mViewPos = 0;
						return true;
					} else if (position == 0 && keyCode == KeyEvent.KEYCODE_DPAD_LEFT
							&& event.getAction() == KeyEvent.ACTION_DOWN) {
						mRecycleView.getItemView(tabsCount - 1).requestFocus();
						mViewPos = tabsCount - 1;
						return true;
					}
					return false;
				}
			});
		}


		@Override
		public int getItemCount() {
			return names != null ? names.length : 0;
		}

		class MyViewHolder extends RecyclerView.ViewHolder {
			TextView textview;
			ImageView cartoonimage;

			public MyViewHolder(View itemView) {
				super(itemView);
				cartoonimage = (ImageView) itemView.findViewById(R.id.cartoon_character);
				textview = (TextView) itemView.findViewById(R.id.model_text);
			}
		}
	}

	/**
	 * 获取指定位置的itemview
	 */
	private View getItemView(int index) {
		return mLayoutManager.findViewByPosition(index);
	}

	/***
	 * 设置焦点到position制定的位置
	 **/
	private void setItemFocus() {
		View view = getItemView(mViewPos);
		if (view == null) {
			handler.sendEmptyMessageDelayed(0, 100);
		} else {
			setHasFocus();
			view.requestFocus();
		}
	}


	/** -----------------------------焦点变换处理----------------------------- **/
	/**
	 * 恢复默认显示
	 */
	private void setDefult() {
		// 把上一个恢复默认
		RelativeLayout relativeLayout = (RelativeLayout) getItemView(mViewPos);
		TextView textView = (TextView) relativeLayout.findViewById(R.id.model_text);
		textView.setBackground(tabdefault);
		textView.setTextColor(bluetext);
	}

	/**
	 * 设置focused状态
	 */
	private void setHasFocus() {
		// 加边框
		RelativeLayout relativeLayout = (RelativeLayout) getItemView(mViewPos);
		TextView textView = (TextView) relativeLayout.findViewById(R.id.model_text);
		textView.setBackground(tabfocused);
		textView.setTextColor(whitetext);
		// 焦点变换回调
		onItemFocusChangeListener.onFocusChange(mViewPos);
	}

	/**
	 * 设置indicator状态
	 **/
	private void setLeaveFocus() {
		RelativeLayout relativeLayout = (RelativeLayout) getItemView(mViewPos);
		TextView textView = (TextView) relativeLayout.findViewById(R.id.model_text);
		textView.setBackground(tabindicator);
		textView.setTextColor(whitetext);

	}


	/** -----------------------------事件接口---------------------------------- **/
	/**
	 * item 点击事件接口
	 *
	 * @param <T>
	 */
	public interface OnItemClickListener<T> {
		void onItemClick(int position, T data);
	}

	/**
	 * 设置点击事件
	 */
	public void setItemClickListener(OnItemClickListener itemClickListener) {
		this.itemClickListener = itemClickListener;
	}

	/**
	 * item 焦点变换
	 */
	public interface OnItemFocusChangeListener {
		void onFocusChange(int position);
	}

	public void setOnItemFocusChangeListener(OnItemFocusChangeListener onItemFocusChangeListener) {
		this.onItemFocusChangeListener = onItemFocusChangeListener;
	}
}
