package com.wasu.cs.ui;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.cs.adapter.GridExAdapterBase;
import com.wasu.cs.model.CatData;
import com.wasu.cs.protocol.CatProtocol;
import com.wasu.cs.widget.ChannelVideoLayout;
import com.wasu.cs.widget.ChannelVideoLayout.PlayIndexChangedListener;
import com.wasu.cs.widget.FocusGridViewEx;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.frescoimagefetchermodule.PauseOnScrollListener;
import com.wasu.module.log.WLog;

import cn.com.wasu.main.R;

/**
 * 带视频小窗口的二级列表页container部分
 * layoutcode为：ShortVideo_List
 * Created by LiuYang on 6/30/15.
 */
public class FragmentChannelNewsList extends FragmentPageBase implements PlayIndexChangedListener{

    private ChannelVideoLayout mVideoLayout;
    private FocusGridViewEx mListView;
    private ChannelNewListAdapter mAdapter;
    private CatProtocol mMoreProtocol;
    /*判断每次显示*/
    private boolean isShowed = false;
    private LayoutInflater lInflater;
    private static final String TAG = FragmentChannelNewsList.class.getSimpleName();
    private int currentIndex = -1;
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_channel_news_list,null);

        mVideoLayout = (ChannelVideoLayout) rootView.findViewById(R.id.channelVideoLayout);
        mVideoLayout.setOnPlayIndexChangedListener(this);
        mListView = (FocusGridViewEx) rootView.findViewById(R.id.listView);

        initListView();
        return rootView;
    }

    @Override
    protected boolean onBackPressed() {
       if(mListView != null){
    	   if(mListView.hasFocus() && mAdapter.getCount() > 0) {
           	mListView.scrollTo(0, 0);
           	mListView.reset();
            mListView.setSelection(0);
               return true;
           }
       }else{
    	   WLog.e(TAG, "mListView == null 被强制GC");
       }
        return false;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mMoreProtocol = getProtocol();

        mAdapter = new ChannelNewListAdapter();
        mListView.setAdapter(mAdapter);

        fetchData();
    }

    @Override
    public void onDestroy() {
    	super.onDestroy();
    	isShowed = false;
    	try {
    		if(mVideoLayout != null){
    			mVideoLayout.removeAllViews();
    			mVideoLayout.finalize();
    		}
		} catch (Throwable e) {
			e.printStackTrace();
		}
    	recycleResource();
    }
    
    @Override
    public void onDestroyView() {
    	super.onDestroyView();
    	isShowed = false;
    	try {
    		if(mVideoLayout != null){
    			mVideoLayout.removeAllViews();
    			mVideoLayout.finalize();
    		}
		} catch (Throwable e) {
			e.printStackTrace();
		}
    	recycleResource();
    }
    
    private void recycleResource(){
    	if(mVideoLayout != null){
    		mVideoLayout.removePlayIndexChangedListener();
    		mVideoLayout = null;
    	}
    	if(mListView != null){
    		mListView = null;
    	}
    	if(mAdapter != null){
    		mAdapter.clearData();
    		mAdapter = null;
    	}
    	if(mMoreProtocol != null){
    		mMoreProtocol.cleanData();
    		mMoreProtocol = null;
    	}
    	if(lInflater != null){
    		lInflater  = null;
    	}
    }
    
    @Override
    public void onPause() {
    	// TODO Auto-generated method stub
    	super.onPause();
    }
    
    @Override
    public void onFetchData(final CatData catData) {
    	if (!isVisible()) {
            return;
        }
    	mVideoLayout.postDelayed(new Runnable() {
			
			@Override
			public void run() {
		    	if (!isVisible()) {
		            return;
		        }
//		        ImageFetcherModule.getInstance().attachImage(catData.getCat().getBgImage(),);
		        mAdapter.setData(catData.getAssets());
		        mAdapter.notifyDataSetChanged();
		        if(getLayoutCode().equalsIgnoreCase(FragmentFactory.SHORT_VIDEO_LIST) && catData.getAssets().size() > 0) {
		            mVideoLayout.setVisibility(View.VISIBLE);
		            mVideoLayout.setTag(mJsonUrl);
		            mVideoLayout.setData(catData.getAssets());
		        }				
			}
		}, 400);
    }

    @Override
    public void onSelected() {
        super.onSelected();
//        getBgImageView().setImageResource(R.drawable.news_list_bg);
//        mVideoLayout.setOffScreen(false);
    }

    @Override
    public void onUnSelected() {
        super.onUnSelected();
//        mVideoLayout.setOffScreen(true);
    }
    
    @Override  
    public void setUserVisibleHint(boolean isVisibleToUser) {  
        super.setUserVisibleHint(isVisibleToUser);  
//        mVideoLayout.setOffScreen(isVisibleToUser);
        if (isVisibleToUser) {  
            //相当于Fragment的onResume
	        isShowed = true;
	        if (mVideoLayout != null) {
		        mVideoLayout.setOffScreen(false);
		        if ( mAdapter.mIndex > 0) {
			        CatData.AssetElement itemdata = mCatData.getAssets().get(mAdapter.mIndex);
			        ImageView imageView = (ImageView) mVideoLayout.findViewById(R.id.imageView);
			        FrescoImageFetcherModule.getInstance().attachImage(itemdata.getPicUrl(), imageView, getResources().getDimensionPixelSize(R.dimen.d_5dp));
		        }
        	}
        } else {  
            //相当于Fragment的onPause
        	if(mVideoLayout != null){
        		mVideoLayout.stopPlaying();
        	}
        	if(isShowed){
        		if(mVideoLayout !=  null){
        		mVideoLayout.setOffScreen(true);
        		/**页面被切换，清除所有的index TAG**/
        		if(mAdapter != null && currentIndex >= 0){
        			mAdapter.clearIndexTag(currentIndex);
        			currentIndex = -1;
        			}
        		}
        		isShowed = false;
        	}
        }  
    }  
    
    @Override
    public void onResume() {
    	super.onResume();
    }

    private void initListView() {
    	mListView.setFocusHightlightDrawable(R.drawable.tv_select_focus);
		mListView.postAnimation(200, null);
//		mListView.setFocusShadowDrawable(R.drawable.focus_shadow);
//		mListView.setOnScrollListener(new PauseOnScrollListener(ImageFetcherModule.getInstance().getImageLoader(), true, true));
		mListView.setOnScrollListener(new PauseOnScrollListener(true, true));
		lInflater = LayoutInflater.from(getActivity());
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //view.performClick();
            	if(mVideoLayout.isPlaying() && currentIndex == i){
            		mVideoLayout.toggleFullScreen();
            	}else{
            		mVideoLayout.playVideo(i);
            	}
            }
        });
        mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                checkNextPageData(i);
//                mListView.setFocusItem(view);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            		
            }
        });
		mListView.setOnGridViewColumnListener(new FocusGridViewEx.FocusGridViewColumnListener() {
			@Override
			public void onColumnBegin() {
				mVideoLayout.requestFocus();
			}

			@Override
			public void onColumnEnd() {
			}
		});
    }

    private void checkNextPageData(int position) {
        int count = mAdapter.getCount();
        if(getProtocol().getTotalSize() > count &&
           position > count / 2){
        	getProtocol().nextPage();
        }
        
    }

     private class ChannelNewListAdapter extends GridExAdapterBase {

        @SuppressWarnings("unused")
		@Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
//            ChannelNewsListItem item = null;
//            if(view == null) {
//                item = new ChannelNewsListItem(getActivity());
//            }
//            else {
//                item = (ChannelNewsListItem)view;
//            }
//            
//            CatData.AssetElement itemData = (CatData.AssetElement) getItemData(i);
//            item.setData(itemData);
//            
//            try {
//				JSONStringer js = new JSONStringer();
//				js.object();
//				js.key("playIndex").value(i);
//				js.key("jsonUrl").value(mJsonUrl + "&page=1&psize=100");
//				js.endObject();
//				
//				item.setTag(js.toString());
//			} catch (JSONException e) {
//				e.printStackTrace();
        	
//			}
        	if(convertView != null){
				String tag = String.valueOf(convertView.getTag(R.id.tag_second));
				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 = (SimpleDraweeView) convertView.findViewById(R.id.ivPic);
        		viewHolder.mTextView = (TextView) convertView.findViewById(R.id.name);
        		viewHolder.playingTAG = (TextView) convertView.findViewById(R.id.playingTAG);
        		/**防止GridView被reset后清除点index TAG**/
        		if(position == currentIndex){
        			viewHolder.playingTAG.setVisibility(View.VISIBLE);
        		}
        		convertView.setTag(R.id.tag_first,viewHolder);
        	}else{
        		viewHolder = (ViewHolder) convertView.getTag(R.id.tag_first);
        	}
        	
        	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_second,position);
            return convertView;
        }
        public class ViewHolder{
        	private TextView mTextView;
            private SimpleDraweeView mImageView;
            private TextView playingTAG;
        }
        /**记录上次播放的index**/
        private int mIndex = -1;
        /**隐藏上次的播放index的TAG，显示本次的index TAG**/
        public void setIndexPlaying(int index){
        	if(mIndex != -1 && mIndex != index){
        		View viewItemLast = getCurrentPlayingItem(mIndex);
        		if(viewItemLast != null){
                	TextView txtLast = (TextView) viewItemLast.findViewById(R.id.playingTAG);  
                	txtLast.setVisibility(View.GONE);
                }
        	}
        	mIndex = index;
            View viewItem = getCurrentPlayingItem(index);  
            if(viewItem != null){
            	TextView txt = (TextView) viewItem.findViewById(R.id.playingTAG);
            	txt.setVisibility(View.VISIBLE);

            }
        }
        /**
         * 当前的页面被切换，视频停止播放，清楚index TAG
         * @param index
         */
        public void clearIndexTag(int index){
        	View mView = getCurrentPlayingItem(index);
        	if(mView != null){
        		TextView mTxt = (TextView) mView.findViewById(R.id.playingTAG);  
        		mTxt.setVisibility(View.GONE);
        	}
        }
        /**获取对应index的ItemView**/
        private View getCurrentPlayingItem(int index){
        	// 如添加headerview后 firstview就是hearderview  
            // 所有索引+1 取第一个view  
            // View view = listview.getChildAt(index - visiblePosition + 1);  
        	int visiblePosition = mListView.getFirstVisiblePosition(); 
        	return mListView.getChildAt(index - visiblePosition);
        }
    }
    
    /**
     * 播放器回调当前播放的index
     */
	@Override
	public void onCurrentIndex(int index) {
		// TODO Auto-generated method stub
		currentIndex = index;
		if(mListView != null){
//			mListView.smoothScrollToPosition(index);
			mAdapter.setIndexPlaying(index);
		}
	}

	/**
	 * 最后一个资产播放完成会调用，清除“播放中”指示器
	 * @param index
	 */
	@Override
	public void cleanPlayIndex(int index) {
		if(mAdapter != null){
			mAdapter.clearIndexTag(index);
		}
		currentIndex = -1;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		//在apk出现意外终止时不保存现场，避免在APK挂掉马上恢复时出现异常
//		super.onSaveInstanceState(outState);
	}
}
