package com.wasu.cs.ui;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.cs.model.CartoonListModel;
import com.wasu.cs.model.CatData;
import com.wasu.cs.mvp.IView.ICartoonListView;
import com.wasu.cs.mvp.presenter.CartoonListPresenter;
import com.wasu.cs.protocol.CatProtocol;
import com.wasu.cs.utils.FocusAnimUtils;
import com.wasu.cs.widget.CartoonRecyclerView;
import com.wasu.cs.widget.FocusGridLayoutManager;
import com.wasu.module.log.WLog;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewAdapter;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewHolder;
import com.wasu.widgets.focuswidget.FocusRecyclerView;

import java.util.ArrayList;
import java.util.List;

import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

/**
 * Created by chenming on 2016/11/8.
 *
 * @Description: 动画列表页
 * @email chenming@wasu.com
 */

public class ActivityCartoon extends ActivityBase implements ICartoonListView {
	private static final String TAG = "ActivityCartoon";
	//UI wediget
	private ImageView ivfavourite, ivsearch, ivup, ivdown;
	private CartoonRecyclerView mCartoonTab;
	private FocusRecyclerView mCartoonGridview;
	//adapter
	private CartoonGridAdapter mCartoonGridAdapter;
	//presenter
	private CartoonListPresenter mPresenter;
	//private CatProtocol catprotocol;
	private List<CatProtocol> mCatProtocolList;
	//test data
	private CartoonListModel cartoonData;
	private SparseArray<CatData> mCatData;
	private Handler handler;

	//状态标记
	private int tabcount = 0;
	private int tabIndex = 0;

	@Override
	protected void doCreate(Bundle savedInstanceState) {
		WLog.i(TAG,"doCreate()");

		initUI();
		initAdapter();
		initListeners();
		fetchData(getIntent().getStringExtra(IntentConstant.DATAURI.value()));
	}


	private void fetchData(String url) {
		mPresenter = new CartoonListPresenter();
		mPresenter.attachView(this);
		mPresenter.getCartoonListData(url, new Handler());

		mCatProtocolList = new ArrayList<>();
	}


	private void initUI() {
		setContentView(R.layout.activity_catoon);
		ivfavourite = (ImageView) findViewById(R.id.cartoon_favourate);
		ivsearch = (ImageView) findViewById(R.id.cartoon_search);
		ivup = (ImageView) findViewById(R.id.arrow_up);
		ivdown = (ImageView) findViewById(R.id.arrow_down);
		mCartoonTab = (CartoonRecyclerView) findViewById(R.id.cartoon_tab);
		mCartoonGridview = (FocusRecyclerView) findViewById(R.id.cartoon_grid);
	}

	private void initAdapter() {
		//init tab
		mCartoonTab.setLayoutAndDrawable(R.layout.item_cartoon_tab,
				getResources().getDrawable(R.drawable.cartoon_btn_normal),
				getResources().getDrawable(R.drawable.cartoon_btn_focused),
				getResources().getDrawable(R.drawable.cartoon_btn_normal));

		//mCartoonTab.setRightFocusView(mCartoonGridview);


		//init grid
		mCartoonGridview.setHasFixedSize(true);
		FocusGridLayoutManager focusGridLayoutManager = new FocusGridLayoutManager(this, 5);
		focusGridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
		mCartoonGridview.setLayoutManager(focusGridLayoutManager);
		mCartoonGridview.addItemDecoration(new RecyclerView.ItemDecoration() {
			@Override
			public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
				super.getItemOffsets(outRect, view, parent, state);
				outRect.left = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_5dp);
				outRect.right = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_5dp);
				outRect.bottom = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_13dp);
				outRect.top = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_13dp);
			}
		});
		mCartoonGridview.setNextFocusLeftId(R.id.cartoon_tab);

	}

	private void initListeners() {
		View.OnClickListener listener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
					case R.id.cartoon_search:
						IntentMap.startIntent(ActivityCartoon.this,
								null,
								cartoonData.getData().getSearch().getLayout(),
								cartoonData.getData().getSearch().getJsonUrl(),
								null);
						break;
					case R.id.cartoon_favourate:
						IntentMap.startIntent(ActivityCartoon.this,
								null,
								"Children_Fav",
								"",
								null);
						break;
					default:
						break;
				}
			}
		};
		ivfavourite.setOnClickListener(listener);
		ivsearch.setOnClickListener(listener);

		View.OnKeyListener keyListener = new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() == KeyEvent.ACTION_DOWN) {
					if (mCartoonGridview != null) {
						mCartoonGridview.requestFocus();
						return true;
					}
				}
				return false;
			}
		};
		ivfavourite.setOnKeyListener(keyListener);
		ivsearch.setOnKeyListener(keyListener);
		mCartoonTab.setOnItemFocusChangeListener(new CartoonRecyclerView.OnItemFocusChangeListener() {
			@Override
			public void onFocusChange(int position) {
				/*if (0 == mCartoonTab.getLayoutManager().findFirstCompletelyVisibleItemPosition()
						&& mCartoonTab.getLayoutManager().findLastCompletelyVisibleItemPosition() < mCartoonTab.getChildCount() - 1) {
					ivup.setVisibility(View.INVISIBLE);
					ivdown.setVisibility(View.VISIBLE);
				} else if (mCartoonTab.getLayoutManager().findFirstCompletelyVisibleItemPosition() > 0 &&
						mCartoonTab.getLayoutManager().findLastCompletelyVisibleItemPosition() == mCartoonTab.getChildCount() - 1) {
					ivdown.setVisibility(View.INVISIBLE);
					ivup.setVisibility(View.VISIBLE);
				} else {
					ivdown.setVisibility(View.INVISIBLE);
					ivup.setVisibility(View.INVISIBLE);
				}*/
				if (tabIndex == position) {
					return;
				} else {
					updataGridView(position);
				}
				tabIndex = position;
			}
		});
	}

	/**
	 * when tab item focus change,update data or fetch data and cache in memeory
	 * @param index
	 */
	private void updataGridView(int index){
		if (mCatData.get(index) != null) {
			mCartoonGridAdapter.setData(mCatData.get(index).getAssets());
			mCartoonGridAdapter.notifyDataSetChanged();
		} else {
			mPresenter.getCatData(cartoonData.getData().getList().get(index).getJsonUrl(),index);
		}

	}
	private void fetchNextPageData() {
		mCatProtocolList.get(tabIndex).nextPage();

	}


	@Override
	public void onGetDataSucceed(CartoonListModel cartoonData) {
		this.cartoonData = cartoonData;
		tabcount = cartoonData.getData().getList().size();
		mCatData = new SparseArray<>(tabcount);
		List<String> tabname = new ArrayList<>();
		mCartoonGridAdapter = new CartoonGridAdapter(mCartoonGridview, this);
		mCartoonGridview.setAdapter(mCartoonGridAdapter);
		mPresenter.getCatData(cartoonData.getData().getList().get(0).getJsonUrl(),0);//首次加载默认加载第一个tab下的数据
		for (int i = 0; i < tabcount; i++) {
			tabname.add(cartoonData.getData().getList().get(i).getTitle());//添加名称
		}
		mCartoonTab.setData(tabname);
		mCartoonTab.postDelayed(new Runnable() {
			@Override
			public void run() {
				View view = mCartoonTab.getLayoutManager().findViewByPosition(0);
				if (view != null) {
					view.requestFocus();
				}
			}
		}, 300);

	}

	@Override
	public void onGetCatData(CatData catData,int index) {
		if (catData == null){
			return;
		}
		if (mCatData!=null){
			mCatData.put(index,catData);
			updataGridView(index);
		}

	}

	@Override
	public void onGetDataFailed(Throwable throwable) {
		Toast.makeText(ActivityCartoon.this, "服务器开小差了，请稍后重试哦~", Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		recycleMemory();
	}

	private void recycleMemory() {
		if (mCartoonGridAdapter != null) {
			mCartoonGridAdapter = null;
		}
		if (mPresenter != null) {
			mPresenter = null;
		}
		if (mCatProtocolList != null) {
			mCatProtocolList = null;
		}
		if (cartoonData != null) {
			cartoonData = null;
		}
		if (mCatData != null) {
			mCatData = null;
		}
		if (handler != null) {
			handler = null;
		}
		System.gc();
	}

	private class CartoonGridAdapter extends BaseFocusRecyclerViewAdapter<CatData.AssetElement> {
		private Context mContext;

		public CartoonGridAdapter(FocusRecyclerView recyclerView, Context context) {
			super(recyclerView);
			mContext = context;
		}

		@Override
		protected BaseFocusRecyclerViewHolder createItem(ViewGroup parent, int viewType) {
			View view = LayoutInflater.from(mContext).inflate(R.layout.item_cartoon_grid, null);
			return new GridItemViewHolder(view, getItemParent(), getItemListener());
		}

		@Override
		protected void bindData(final BaseFocusRecyclerViewHolder holder, final int position) {

			((GridItemViewHolder) holder).tv.setText(getItemData(position).getTitle());
			((GridItemViewHolder) holder).iv.setImageURI(getItemData(position).getPicUrl());
			((GridItemViewHolder) holder).itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					mCartoonTab.setLeaveTag();
					FocusAnimUtils.animItem(v, hasFocus, 1.15f);
				}
			});
			((GridItemViewHolder) holder).itemView.setOnKeyListener(new View.OnKeyListener() {
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if (event.getAction() == KeyEvent.ACTION_DOWN){
						switch (keyCode){
							case KeyEvent.KEYCODE_DPAD_UP:
								if (position < 5 && ivfavourite != null) {
									ivsearch.requestFocus();
									return true;
								}
								break;
							case KeyEvent.KEYCODE_DPAD_RIGHT:
								if (position + 1 < getItemCount() && mCartoonGridview.findViewHolderForAdapterPosition(position + 1) != null) {//gridview中向右移动 焦点自动下移到下一排第一个
									mCartoonGridview.findViewHolderForAdapterPosition(position + 1).itemView.requestFocus();
									return true;
								}
								break;
							case KeyEvent.KEYCODE_DPAD_DOWN:
								if (getItemCount() - position < 6 && mCartoonGridview != null) {
									mCartoonGridview.scrollToPosition(0);
									mCartoonGridview.postDelayed(new Runnable() {
										@Override
										public void run() {
											mCartoonGridview.getChildAt(0).requestFocus();

										}
									},300);
									return true;
								}
								break;
							default:
								break;
						}
					}
					return false;
				}
			});
			((GridItemViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					String layout = getItemData(position).getLayout();
					if (layout.contains("Series") || layout.contains("Movie")) {
						IntentMap.startIntent(ActivityCartoon.this,
								null,
								"Children_Detail",
								getItemData(position).getJsonUrl(),
								null);
					} else {
						IntentMap.startIntent(ActivityCartoon.this,
								null,
								getItemData(position).getLayout(),
								getItemData(position).getJsonUrl(),
								null);
					}
				}
			});
		}

		class GridItemViewHolder extends BaseFocusRecyclerViewHolder {
			View view;
			SimpleDraweeView iv;
			TextView tv;

			public GridItemViewHolder(View itemView, FocusRecyclerView parent, BaseFocusRecyclerViewAdapter.OnItemListener itemlistener) {
				super(itemView, parent, itemlistener);
				itemView.setFocusable(true);
				view = itemView;
				iv = (SimpleDraweeView) itemView.findViewById(R.id.catoon_imageview);
				tv = (TextView) itemView.findViewById(R.id.tv_cat_item_name);
			}

			@Override
			protected View getView() {
				return view;
			}
		}
	}

}
