package com.wasu.cs.ui;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.wasu.cs.adapter.GridExAdapterBase;
import com.wasu.cs.model.CatData;
import com.wasu.cs.protocol.CatProtocol;
import com.wasu.cs.widget.FocusGridViewEx;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.widget.FocusLinearLayout;

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

/**
 * 带视频小窗口的二级列表页container部分,把视频小窗口只显示图片 
 * layoutcode为：ShortVideo_List1
 * @author Danxingxi created on 2016/1/13
 *
 */
public class FragmentChannelShortVideoList extends FragmentPageBase {

	private FocusGridViewEx mListView;
	private View rootView;
	private CatProtocol mMoreProtocol;
	/** 显示在左边的海报 **/
	private ImageView img_left ,playIcon;
	private LayoutInflater lInflater;
	private FocusLinearLayout mFocusLayout;
	private ChannelShortVideoAdapter mAdapter;
	private String catJsonUrl;
	private TextView name;
	private int tempIndex = 0;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_channel_short_video, null);
		initView();
		return rootView;
	}

	/**
	 * 请求数据，创建和设置adapter显示数据内容
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lInflater = LayoutInflater.from(getActivity());
		mMoreProtocol = getProtocol();
		mAdapter = new ChannelShortVideoAdapter();
		mListView.setAdapter(mAdapter);
		fetchData();
	}

	/**
	 * 在创建Fragment时请求数据成功后的回调
	 */
	@Override
	public void onFetchData(final CatData catData) {
		// TODO Auto-generated method stub
		if (catData !=null && catData.getAssets().size() > 0) {
			if(img_left != null){
				FrescoImageFetcherModule.getInstance().attachImage(catData.getAssets().get(0).getPicUrl(), img_left, getResources().getDimensionPixelSize(R.dimen.d_5dp));
				name.setText(catData.getAssets().get(0).getName());
			}
			getHandler().postDelayed(new Runnable() {

				@Override
				public void run() {
					if(mAdapter!= null && catData != null){
						mAdapter.setData(catData.getAssets());
						mAdapter.notifyDataSetChanged();
					}
//					playIcon.setVisibility(View.VISIBLE);
				}
			}, 400);
		}
	}

	private void initView(){
		
		img_left = (ImageView) rootView.findViewById(R.id.img_left);
		playIcon = (ImageView) rootView.findViewById(R.id.playIcon);
		name = (TextView) rootView.findViewById(R.id.name);
		
		mFocusLayout = (FocusLinearLayout) rootView.findViewById(R.id.focusLayout);
		mFocusLayout.setFocusRealId(R.id.img_left);
		mFocusLayout.setFocusHighlightDrawable(R.drawable.tv_select_focus);
		mFocusLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(tempIndex >= 0){
					toPlay(tempIndex);
				}
			}
		});
		
		mListView = (FocusGridViewEx) rootView.findViewById(R.id.listView);
		mListView.setFocusHightlightDrawable(R.drawable.tv_select_focus);
		mListView.postAnimation(200, null);
		mListView.setOnScrollListener(new com.wasu.frescoimagefetchermodule.PauseOnScrollListener(true, true));
		
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				// TODO Auto-generated method stub
				toPlay(i);
			}
		});
		
		mListView.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
				// TODO Auto-generated method stub
				/**避免左边海报图重复加载**/
				if(i != tempIndex){

					FrescoImageFetcherModule.getInstance().attachImage(mCatData.getAssets().get(i).getPicUrl(), img_left, getResources().getDimensionPixelSize(R.dimen.d_5dp));
					name.setText(mCatData.getAssets().get(i).getName());
				}
				tempIndex = i;
				checkNextPageData(i);
//				Glide.with(getActivity()).load(mCatData.getAssets().get(i).getPicUrl()).dontAnimate().into(img_left);
			}

			@Override
			public void onNothingSelected(AdapterView<?> adapterView) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	/**
	 * 跳转到播放器播放视频
	 * @param i 选中要播放的index
	 */
	private void toPlay(int i){
		Intent intent = new Intent();
		intent.putExtra(IntentConstant.PLAY_TYPE.value(), ActivityPlayer.PLAY_TYPE_LOOP);
		intent.putExtra(IntentConstant.PLAY_INDEX.value(), i);
		intent.putExtra(ActivityPlayer.ASSET_URL, mJsonUrl);
		IntentMap.startIntent(getActivity(), intent, null, null, ActivityPlayer.class);
	}
	
	/**
	 * 检查是否还有下一页数据，有就加载下一页
	 * @param position
	 */
	private void checkNextPageData(int position) {
        int count = mAdapter.getCount();
        if(getProtocol().getTotalSize() > count &&
           position > count / 2){
        	getProtocol().nextPage();
        }
        
    }
	
	@Override
	protected boolean onBackPressed() {
		if(mListView != null){
			mListView.scrollTo(0, 0);
			mListView.setSelection(0);
			mListView.reset();
			FrescoImageFetcherModule.getInstance().attachImage(mCatData.getAssets().get(0).getPicUrl(), img_left, getResources().getDimensionPixelSize(R.dimen.d_5dp));
			name.setText(mCatData.getAssets().get(0).getName());
		}
		return false;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		clearResource();
	}
	
	private void clearResource(){
		if(mListView != null){
			mListView = null;
		}
		if(rootView != null){
			rootView = null;
		}
		if(mMoreProtocol != null){
			mMoreProtocol = null;
		}
		if(img_left != null){
			img_left = null;
		}
		if(playIcon != null){
			playIcon = null;
		}
		if(lInflater != null){
			lInflater = null;
		}
		if(mFocusLayout != null){
			mFocusLayout = null;
		}
		if(mAdapter != null){
			mAdapter.clearData();
			mAdapter = null;
		}
		if(catJsonUrl != null){
			catJsonUrl = null;
		}
		if(name != null){
			name = null;
		}
	}
	
	private class ChannelShortVideoAdapter extends GridExAdapterBase {

		@SuppressWarnings("unused")
		@Override
		public View getView(int position, View convertView, ViewGroup viewGroup) {
			
			if(convertView != null){
				String tag = String.valueOf(convertView.getTag(R.id.tag_second02));
				if(!TextUtils.isEmpty(tag)){
					if(tag.equalsIgnoreCase(String.valueOf(position))){
						return convertView;
					}
				}
			}
			
			final CatData.AssetElement itemData = (CatData.AssetElement) getItemData(position);
			ViewHolder viewHolder = null;
			if (null == viewHolder) {
				viewHolder = new ViewHolder();
				convertView = lInflater.inflate(R.layout.item_channel_news_list, null);
				viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.ivPic);
				viewHolder.mTextView = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(R.id.tag_first02, viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag(R.id.tag_first02);
			}

			if (null != itemData) {
				/*Glide.with(getActivity()).load(itemData.getPicUrl()).dontAnimate().transform(
						new GlideRoundTransform(getActivity(), getResources().getDimensionPixelSize(R.dimen.d_5dp)))
						.into(viewHolder.mImageView);*/
				FrescoImageFetcherModule.getInstance().attachImage(itemData.getPicUrl(), viewHolder.mImageView, getResources().getDimensionPixelSize(R.dimen.d_5dp));
				viewHolder.mTextView.setText(itemData.getTitle());
			}
			convertView.setTag(R.id.tag_second02, position);
			return convertView;
		}

		private final class ViewHolder {
			 TextView mTextView;
			 ImageView mImageView;
		}

	}
}
