package com.wasu.cs.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
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.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.cs.model.ChildrenChannelModel;
import com.wasu.cs.module.ChildFavModule;
import com.wasu.cs.mvp.IView.IChildrenHomeView;
import com.wasu.cs.mvp.presenter.ChildrenHomePresenter;
import com.wasu.cs.utils.BitmapUtils;
import com.wasu.cs.utils.FocusAnimUtils;
import com.wasu.cs.widget.FocusGridLayoutManager;
import com.wasu.cs.widget.HorentialFocusRecycleView;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.log.WLog;
import com.wasu.statistics.WasuStatistics;
import com.wgallery.android.IWGalleryAdapter;
import com.wgallery.android.WGallery;

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

import basic.db.model.DBProgramChildFavorite;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;
import us.feras.ecogallery.EcoGalleryAdapterView;

import static cn.com.wasu.main.R.id.cartoon_focused;
import static com.wasu.cs.model.ChildrenRecommendModel.DataBean.Cat;

/**
 * Created by chenming on 2016/11/1.
 *
 * @Description: 新版少儿频道首页
 * @email chenming@wasu.com
 */

public class ActivityChildren extends ActivityBase implements IChildrenHomeView {
	private static final String TAG = "ActivityChildren";
	//UI控件
	private ImageView ivcartoonfocused,ivfavourite,ivsearch;
	private TextView infotext;
	private ScrollView mScrollView;
	private WGallery mCartoonGallery;
	private HorentialFocusRecycleView mModelEnterTab;
	private RecyclerView mChildRecGridView;
	private FrameLayout mFrameLayout;
	//动效
	private TranslateAnimation shakeAnim;
	private Animation animation;
	//音效
	private SoundPool mSoundPool;
	private int audioId;
	//数据集合
	private WGalleryAdapter mWGalleryAdapter;
	//private GridItemAdapter mRecCatAdapter;
	private SparseArray<GridItemAdapter> adapterList;
	private List<ChildrenChannelModel.DataBean.BodyBean.CartoonsBean> cartoonsBeanList;
	private List<ChildrenChannelModel.DataBean.BodyBean.EntrysBean> entrysBeanList;
	private ChildrenChannelModel.DataBean.BodyBean.InfoBarBean infoBar;
	private SparseArray<List<Cat>> recmdList;
	//private List<Cat> mFavList ;
	private List<DBProgramChildFavorite> mFavourates;
	private  int entrycount;
	private final String staticestag="少儿频道";
	//private ChildrenFavQueryAsyncTask queryFavAsyncTask;
	//状态标记
	private int tabIndex = 0;
	private ImageView headerFocusView;//remerber user's focus icon
	//presenter
	private ChildrenHomePresenter presenter;

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

		presenter = new ChildrenHomePresenter();
		presenter.attachView(this);
		presenter.getChildrenData(getIntent().getStringExtra(IntentConstant.DATAURI.value()));
		initUI();
		initData();
		setViewListeners();
		initAnimation();
		initAudio();
	}

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

		animation = AnimationUtils.loadAnimation(this,R.anim.scaleinandout);
		//ivcartoonfocused.setAnimation(animation);
	}

	private void initAudio() {
		mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
		audioId = mSoundPool.load(this, R.raw.focus_audio, 1);
	}

	Bitmap bitmap = null;
	private void initUI() {
		setContentView(R.layout.activity_children_home);
		ImageView bg = (ImageView) findViewById(R.id.bg_iv);
		bitmap = BitmapUtils.readBitMapByDecodeStream(this,R.drawable.children_bg);
		bg.setImageBitmap(bitmap);
		infotext = (TextView) findViewById(R.id.welcome_text);
		ivfavourite = (ImageView) findViewById(R.id.cartoon_favourate);
		ivsearch = (ImageView) findViewById(R.id.cartoon_search);
		ivcartoonfocused= (ImageView) findViewById(cartoon_focused);
		mScrollView = (ScrollView) findViewById(R.id.scrollview);
		mCartoonGallery = (WGallery) findViewById(R.id.cartoon_gallery);
		mModelEnterTab = (HorentialFocusRecycleView) findViewById(R.id.children_model_enter);
		//mChildRecGridView = (FocusRecyclerView) findViewById(R.id.children_home_grid);
		mChildRecGridView = (RecyclerView) findViewById(R.id.children_home_grid);
		mFrameLayout = (FrameLayout) findViewById(R.id.btnFrameLayout);
	}

	private void initData() {
		//queryFavAsyncTask = new ChildrenFavQueryAsyncTask();//query children favourate list
		//init catton loop weidget
		mCartoonGallery.setNextFocusDownId(R.id.children_model_enter);
		//init model enter weidget
		mModelEnterTab.setLayoutAndDrawable(R.layout.item_children_model_enter,
				getResources().getDrawable(R.drawable.entey_normal),
				getResources().getDrawable(R.drawable.entry_focused),
				getResources().getDrawable(R.drawable.entry_indicator));
		mModelEnterTab.setParentscroll(mScrollView);
		mModelEnterTab.setUpFocusView(mCartoonGallery);
		mModelEnterTab.setDownFocusView(mChildRecGridView);

		//init grid recyclerview
		mChildRecGridView.setHasFixedSize(true);
		//mChildRecGridView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
		FocusGridLayoutManager gridLayoutManager = new FocusGridLayoutManager(this, 6);
		//gridLayoutManager.setSmoothScrollbarEnabled(true);
		gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
		mChildRecGridView.setLayoutManager(gridLayoutManager);
		mChildRecGridView.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_10dp);
				outRect.right = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_10dp);
				outRect.bottom = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_20dp);
				outRect.top = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_20dp);

			}
		});
		//mRecCatAdapter = new GridItemAdapter(ActivityChildren.this);
		//mChildRecGridView.setAdapter(mRecCatAdapter);
		adapterList = new SparseArray<>();
		mChildRecGridView.setNextFocusUpId(R.id.children_model_enter);
	}

	private void setViewListeners() {
		View.OnClickListener clickListener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
					case R.id.cartoon_favourate:
						IntentMap.startIntent(ActivityChildren.this,
								null,
								infoBar.getCollect().getLayout(),
								infoBar.getCollect().getJsonUrl(),
								null);
						WasuStatistics.getInstance().columnClick(staticestag,"收藏","");
						break;
					case R.id.cartoon_search:
						IntentMap.startIntent(ActivityChildren.this,
								null,
								infoBar.getSearch().getLayout(),
								infoBar.getSearch().getJsonUrl(),
								null);
						WasuStatistics.getInstance().columnClick(staticestag,"搜索","");
						break;
					default:
						break;
				}
			}
		};
		View.OnKeyListener onKeyListener = new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
					if (mCartoonGallery != null && mWGalleryAdapter != null && mWGalleryAdapter.getCount() > 0) {
						mCartoonGallery.requestFocus();
						return true;
					}else {
						return true;
					}
				}
				return false;
			}
		};
		View.OnFocusChangeListener focusChangeListener = new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					headerFocusView = (ImageView) v;
					playSoundEffect();
				}
			}
		};
		ivsearch.setOnFocusChangeListener(focusChangeListener);
		ivfavourite.setOnFocusChangeListener(focusChangeListener);
		ivsearch.setOnKeyListener(onKeyListener);
		ivfavourite.setOnKeyListener(onKeyListener);
		ivsearch.setOnClickListener(clickListener);
		ivfavourite.setOnClickListener(clickListener);

		mFrameLayout.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					if (headerFocusView != null) {
						headerFocusView.requestFocus();
					} else {
						ivsearch.requestFocus();
					}
				}
			}
		});

		mCartoonGallery.setOnItemClickListener(new EcoGalleryAdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(EcoGalleryAdapterView<?> ecoGalleryAdapterView, View view, int i, long l) {
				//跳转动画明星页
				int pos = i % cartoonsBeanList.size();//将循环滚动的索引转换为真实的索引
				final String layout = cartoonsBeanList.get(pos).getLayout();
				if (layout.contains("Detail_Series") || layout.contains("Detail_Movie")) {
					IntentMap.startIntent(ActivityChildren.this,
							null,
							"Children_Detail",
							cartoonsBeanList.get(pos).getJsonUrl(),
							null);
					WasuStatistics.getInstance().columnClick(staticestag,cartoonsBeanList.get(pos).getTitle(),cartoonsBeanList.get(pos).getCatId()+"");
				} else {
					IntentMap.startIntent(ActivityChildren.this,
							null,
							cartoonsBeanList.get(pos).getLayout(),
							cartoonsBeanList.get(pos).getJsonUrl(),
							ActivityCartoonStar.class);
					WasuStatistics.getInstance().columnClick(staticestag,cartoonsBeanList.get(pos).getTitle(),cartoonsBeanList.get(pos).getCatId()+"");
				}
			}
		});
		

		mModelEnterTab.setOnItemFocusChangeListener(new HorentialFocusRecycleView.OnItemFocusChangeListener() {
			@Override
			public void onFocusChange(int position) {
				playSoundEffect();
				if (null != recmdList) {
					if (tabIndex == position) {
						return;
					} else if (position == recmdList.size()-1){
						queryFavHis();
						updataAdapter(position);
						//mRecCatAdapter.setCatList(mFavList);
						//mRecCatAdapter.notifyDataSetChanged();
						tabIndex = position;
					}else {
						updataAdapter(position);
						//updataRecData(position);
					}
					WasuStatistics.getInstance().columnClick(staticestag,entrysBeanList.get(position).getTitle(),entrysBeanList.get(position).getCatId()+"");
				}
			}
		});

		mModelEnterTab.setItemClickListener(new HorentialFocusRecycleView.OnItemClickListener() {
			@Override
			public void onItemClick(int position, Object data) {
				//跳转少儿频道各个入口
				IntentMap.startIntent(ActivityChildren.this,
						null,
						entrysBeanList.get(position).getLayout(),
						entrysBeanList.get(position).getJsonUrl(),
						null);
				WasuStatistics.getInstance().columnClick(staticestag,entrysBeanList.get(position).getTitle(),entrysBeanList.get(position).getCatId()+"");

			}
		});
	}

	private void playSoundEffect() {
		mSoundPool.play(audioId, 1, 1, 1, 0, 1);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		BitmapUtils.recycleBitmap(bitmap);
		recycleMemory();

	}

	private void recycleMemory() {
		if (shakeAnim != null) {
			shakeAnim = null;
		}
		if (mSoundPool != null) {
			mSoundPool = null;
		}
		if (mWGalleryAdapter != null) {
			mWGalleryAdapter = null;
		}
		if (adapterList != null) {
			adapterList = null;
		}
		if (cartoonsBeanList != null) {
			cartoonsBeanList = null;
		}
		if (entrysBeanList != null) {
			entrysBeanList = null;
		}
		if (infoBar != null) {
			infoBar = null;
		}
		if (recmdList != null) {
			recmdList = null;
		}
		if (presenter != null) {
			presenter = null;
		}
		System.gc();
	}

	@Override
	public void onGetInfoBar(ChildrenChannelModel.DataBean.BodyBean.InfoBarBean infoBar) {
		if (infoBar != null) {
			this.infoBar = infoBar;
			infotext.setText(infoBar.getScrolling_msg());
		}
	}

	@Override
	public void onGetCartoons(final List<ChildrenChannelModel.DataBean.BodyBean.CartoonsBean> cartoonsBeanList) {
		this.cartoonsBeanList = cartoonsBeanList;
		mWGalleryAdapter = new WGalleryAdapter(cartoonsBeanList);
		mCartoonGallery.setAdapter(mWGalleryAdapter);
		mCartoonGallery.postDelayed(new Runnable() {
			@Override
			public void run() {
				mCartoonGallery.requestFocus();
				mCartoonGallery.setSelection(cartoonsBeanList.size() * 10000 + cartoonsBeanList.size() / 2);
			}
		},10);

	}

	@Override
	public void onGetEntrys(List<ChildrenChannelModel.DataBean.BodyBean.EntrysBean> entrysBeanList) {
		entrycount = entrysBeanList.size();
		this.entrysBeanList = entrysBeanList;
		final int count = entrysBeanList.size();
		recmdList = new SparseArray<>(count);
		String[] names = new String[count];
		String[] picurls = new String[count];
		ChildrenChannelModel.DataBean.BodyBean.EntrysBean entrysBean;
		for (int j = 0; j < count; j++) {
			entrysBean = entrysBeanList.get(j);
			names[j] = entrysBean.getTitle();
			picurls[j] = entrysBean.getPicUrl();
		}
		mModelEnterTab.setData(names, picurls);
		mModelEnterTab.setViewPos(count / 2);//初始化让中间的tab获取焦点
	}


	@Override
	public void onGetRecommendData(SparseArray<List<Cat>> catList) {
		this.recmdList = catList;
		final int count = catList.size();
		for (int i = 0; i < count; i++) {
			if (recmdList.get(i).size() > 0) {//when reclist has more than one item,add more item,otherwise don't
				recmdList.get(i).add(new Cat(entrysBeanList.get(i).getJsonUrl(), entrysBeanList.get(i).getLayout()));
			}
			adapterList.put(i,new GridItemAdapter(ActivityChildren.this,recmdList.get(i)));//初始化adapter
		}
		updataAdapter(entrycount/2);
		//updataRecData(count / 2);
	}

	private void updataAdapter(int index){
		if (adapterList.get(index)!=null){
			mChildRecGridView.setAdapter(adapterList.get(index));
			tabIndex = index;
		}
	}
	/*private void updataRecData(int pos) {
		if (recmdList != null && recmdList.get(pos) != null) {
			mRecCatAdapter.setCatList(recmdList.get(pos));
			mRecCatAdapter.notifyDataSetChanged();
			tabIndex = pos;
		}
	}*/

	/**
	 * query children favourate
	 */
	private void queryFavHis(){
		List<Cat> mFavList = new ArrayList<>();
		mFavourates = ChildFavModule.getInstance().readFavorite();
		if (mFavourates == null) {
			return;
		}
		mFavList.clear();
		final int size = mFavourates.size() < 12 ? mFavourates.size() : 11;
		if (size > 0) {//when user has collections,show user's collection,else show the rec data
			DBProgramChildFavorite fav;
			for (int i = 0; i < size; i++) {
				fav = mFavourates.get(i);
				if (fav.showType==0){
					mFavList.add(new Cat(fav.programName,
							fav.playUrl,
							fav.programPic,
							"Player_Wasu"));
				}else {
					mFavList.add(new Cat(fav.programName,
							fav.detailUrl,
							fav.programPic,
							"Children_Detail"));
				}

			}
			mFavList.add(new Cat(entrysBeanList.get(entrycount - 1).getJsonUrl(), entrysBeanList.get(entrycount - 1).getLayout()));
		}
		adapterList.get(entrycount-1).setCatList(mFavList);
	}
	@Override
	public void ongetDataFailed(Throwable throwable) {
		Toast.makeText(ActivityChildren.this, "服务器开小差了，请稍后重试哦~", Toast.LENGTH_SHORT).show();
	}


	private class GridItemAdapter extends RecyclerView.Adapter<GridItemAdapter.GridItemViewHolder> {
		private Context mContext;
		private List<Cat> mCatList;

		public GridItemAdapter(Context context) {
			mContext = context;
		}

		public GridItemAdapter(Context context, List<Cat> catList) {
			mContext = context;
			mCatList = catList;
		}

		public void setCatList(List<Cat> catList) {
			mCatList = catList;
		}

		@Override
		public GridItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			View view = LayoutInflater.from(mContext).inflate(R.layout.item_children_home_rec, null);

			return new GridItemViewHolder(view);
		}

		@Override
		public int getItemCount() {
			return mCatList == null ? 0 : mCatList.size() < 12 ? mCatList.size() : 12;
		}

		@Override
		public void onBindViewHolder(final GridItemViewHolder holder, final int position) {
			if (position == getItemCount() - 1) {//the last item is show more
				if (holder.mImageView != null) {
					holder.mImageView.setImageResource(R.drawable.child_rec_more);
				}
				holder.name.setVisibility(View.GONE);
			} else {
				if (holder.mImageView != null) {
					holder.mImageView.setImageURI(mCatList.get(position).getPicUrl());
				}
				if (holder.name != null) {
					holder.name.setText(mCatList.get(position).getTitle());
				}
			}

			holder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						playSoundEffect();
						mModelEnterTab.setLeaveTag();
					}
					FocusAnimUtils.animItem(v, hasFocus, 1.15f);
				}
			});
			holder.itemView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					String layout = mCatList.get(position).getLayout();
					if (layout.contains("Detail_Series") || layout.contains("Detail_Movie")) {
						IntentMap.startIntent(ActivityChildren.this,
								null,
								"Children_Detail",
								mCatList.get(position).getJsonUrl(),
								null);
					} else if(layout.equals("Player_Wasu")||layout.equals("Detail_News")){
						Intent intent = new Intent();
						intent.putExtra("canOffScreen",true);
						IntentMap.startIntent(ActivityChildren.this,
								intent,
								mCatList.get(position).getLayout(),
								mCatList.get(position).getJsonUrl(),
								null);
					}else {
						IntentMap.startIntent(ActivityChildren.this,
								null,
								mCatList.get(position).getLayout(),
								mCatList.get(position).getJsonUrl(),
								null);
					}

				}
			});
			holder.itemView.setOnKeyListener(new View.OnKeyListener() {
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if (event.getAction() == KeyEvent.ACTION_DOWN) {
						if ((position >= 0 && position <= 5) &&
								keyCode == KeyEvent.KEYCODE_DPAD_UP) {//向上
							if (mModelEnterTab != null) {
								mModelEnterTab.requestFocus();
							}
							return true;
						} else if ((position == 0 || position == 6) && keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {//向左
							v.startAnimation(shakeAnim);
							return true;
						} else if ((position == 5 || position == getItemCount() - 1) && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {//向右
							v.startAnimation(shakeAnim);
							return true;
						}
					}
					return false;
				}
			});
		}

		class GridItemViewHolder extends RecyclerView.ViewHolder {
			SimpleDraweeView mImageView;
			TextView name;

			public GridItemViewHolder(View itemView) {
				super(itemView);
				mImageView = (SimpleDraweeView) itemView.findViewById(R.id.cat_imageview);
				name = (TextView) itemView.findViewById(R.id.tv_cat_item_name);
			}
		}
	}

	private class WGalleryAdapter extends BaseAdapter implements IWGalleryAdapter {
		public WGalleryAdapter(List<ChildrenChannelModel.DataBean.BodyBean.CartoonsBean> listdata) {
			this.listdata = listdata;
		}

		private List<ChildrenChannelModel.DataBean.BodyBean.CartoonsBean> listdata;

		@Override
		public int getCount() {
			return Integer.MAX_VALUE;//用于循环
		}

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

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int count = listdata.size();
			position = position % count;
			if (convertView == null) {
				convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cartoon_character,
						parent, false);
			}
			ImageView iv = (ImageView) convertView.findViewById(R.id.iv);
			FrescoImageFetcherModule.getInstance().attachImage(listdata.get(position).getPicUrl(), iv);
			convertView.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_DOWN:
								if (mModelEnterTab == null) {
									return true;
								} else {
									mModelEnterTab.requestFocus();
									return true;
								}
							case KeyEvent.KEYCODE_DPAD_UP:
								mFrameLayout.requestFocus();
								break;
							default:
								break;
						}
					}
					return false;
				}
			});
			convertView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						playSoundEffect();
						mModelEnterTab.setLeaveTag();
						if (ivcartoonfocused != null) {
							ivcartoonfocused.setVisibility(View.VISIBLE);
							ivcartoonfocused.setAnimation(animation);
							animation.start();
						}
					}else {
						ivcartoonfocused.clearAnimation();
						ivcartoonfocused.setVisibility(View.INVISIBLE);
					}
				}
			});

			return convertView;
		}

		@Override
		public int getChangeAlphaViewId() {
			return 0;
		}


	}

}
