package com.wasu.cs.ui;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.R.integer;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Scroller;
import android.widget.TextView;
import cn.com.wasu.main.R;

import com.wasu.common.WError;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.widget.DetailSeriesSetView;
import com.wasu.cs.widget.DetailSeriesSetView.ItemChangedListner;
import com.wasu.module.datafetch.DataFetchListener.ObjectListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;
import com.wasu.module.log.WLog;

/**
 * 设置电视剧的选集框
 * **/
public class DetailSeriesView extends LinearLayout {
	protected static final String TAG = "DialogWithSeries";
	private final int PSIZE=30;

	/**用于设置历史播放的集数为选中，防止焦点被重新刷掉**/
	private boolean setSelectionDelay=false;
	/** 网络数据请求重试次数 **/
	private int fetchDataRetryCount = 3;
	View []views;
	PagerTabStrip pagerTabStrip;
	ArrayList<View> mViewList=new ArrayList<View>();
	ArrayList<String> mTitleList=new ArrayList<String>();
	Context context;
	
	private GridView gvSeries;
	ViewPager viewPager;
	private DetailSeriesSetView mSeriesSet;
	private onSeriesListener mSeriesListener;
	private int SeriesTotal;//总集数
	private int mHistory_episode=-1;
	public DemandProgram mDemandProgram;
	public interface onSeriesListener{
		public void onChoice(int series);
	}
	public DetailSeriesView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}
	public DetailSeriesView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}
	/**
	 * 设置电视剧的选集框
	 * @param Context 上下文
	 * @param int 总集数
	 * @param demandProgram 详情页信息
	 * @param int 上次播放的集数
	 * @param onSeriesListener 点击的监听
	 * **/
	public DetailSeriesView(Context context, int SeriesTotal,DemandProgram demandProgram, int mHistory_episode, onSeriesListener l) {
		super(context);
		WLog.i(TAG, "totalSeries="+SeriesTotal+",mHistory_episode="+mHistory_episode);
		this.mSeriesListener = l;
		this.SeriesTotal = SeriesTotal;
		this.mHistory_episode = mHistory_episode;
		this.mDemandProgram=demandProgram;
		init(context);
	}
	int prePageIndex=0;
	private void init(final Context context) {
		LayoutInflater.from(context).inflate(R.layout.dialog_with_series, this,true);
		final int viewsize;
		//计算电视剧需要显示的页数
		if(SeriesTotal%PSIZE==0){
			viewsize=SeriesTotal/PSIZE;
		}else{
			viewsize=SeriesTotal/PSIZE+1;
		}
		WLog.i(TAG, "init viewsize="+viewsize);
		//根据页数动态生成对应的UI个数
		views=new View[viewsize];
		//保存对应页的播放地址更新状态
		if(mDemandProgram.updateIndex==null){
			mDemandProgram.updateIndex=new int[viewsize];
		}
		viewPager=(ViewPager)findViewById(R.id.viewpager);
		mSeriesSet=(DetailSeriesSetView)findViewById(R.id.detail_series_set);
		//设置数据为下标显示服务
		mSeriesSet.setDemandProgram(mDemandProgram);
		//实例化每个页
		mViewList.clear();
		for(int i=0;i<viewsize;i++){
			views[i]=LayoutInflater.from(context).inflate(R.layout.item_viewpager_detail_series, null);
			final GridView gridView=(GridView)views[i];
			gridView.setOnKeyListener(new OnKeyListener() {
				
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					gridView.setTag(gridView.getSelectedItemPosition());
					if(event.getAction()==KeyEvent.ACTION_DOWN&&gridView.getAdapter().getCount()>15&&gridView.getSelectedItemPosition()==14&&keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){
						gridView.setSelection(PSIZE/2);
						return true;
					}
					
					//去掉到达选集最后一个时，焦点离开选集框问题
					int arg0 = viewPager.getCurrentItem();
					if (viewsize ==  arg0+1 && gridView.getSelectedItemPosition() == (SeriesTotal - 30 *(arg0)-1) && event.getAction()==KeyEvent.ACTION_DOWN && keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){
						return true;
					}
					
					return false;
				}
			});
			((GridView)views[i]).setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					if (mSeriesListener != null){
						TextView textView=(TextView)(view.findViewById(R.id.item_series_num));
						/*Integer.valueOf(mDemandProgram.getDetailSeriesSet().getSeriesSets().get(position+PSIZE*viewPager.getCurrentItem()))*/
						WLog.i(TAG, "num="+Integer.valueOf(textView.getText().toString()));
						mSeriesListener.onChoice(Integer.valueOf(textView.getText().toString()));
					}	
				}
			});
			mViewList.add(views[i]);
			mTitleList.add((i*PSIZE+1)+"-"+((i+1)*PSIZE+1));
		}
		//设置每个页的ui到viewpager
		viewPager.setAdapter(new PagerAdapter() {
			
			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0==arg1;
			}
			
			@Override
			public int getCount() {
				//WLog.i(TAG, "PagerAdapter getCount="+mViewList.size());
				return mViewList.size();
			}

			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object) {
				// TODO Auto-generated method stub
				container.removeView(mViewList.get(position));
			}

			@Override
			public CharSequence getPageTitle(int position) {
				// TODO Auto-generated method stub
				return mTitleList.get(position);
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				// TODO Auto-generated method stub
				container.addView(mViewList.get(position));
				return mViewList.get(position);
			}
		});
		//设置viewpage翻页效果平滑体验
		ViewPagerScroller scroller1 = new ViewPagerScroller(context);
		scroller1.setScrollDuration(0);
		scroller1.initViewPagerScroll(viewPager);  //这个是设置切换过渡时间为0
		 
		ViewPagerScroller scroller2 = new ViewPagerScroller(context);
		scroller2.setScrollDuration(2000);
		scroller2.initViewPagerScroll(viewPager);//这个是设置切换过渡时间为2秒
		
		//viewpager翻页时，做对应的UI处理
		viewPager.addOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				WLog.i(TAG, "onPageSelected arg0="+arg0+",mDemandProgram.updateIndex[arg0]="+mDemandProgram.updateIndex[arg0]+",setSelectionDelay="+setSelectionDelay);
				//当前页没有加载过数据
				if(mDemandProgram.updateIndex[arg0]==0){
					views[arg0].setVisibility(View.INVISIBLE);
					loadSeriesInfo(arg0);
				}else{
					gvSeries	 = (GridView) views[arg0];
					gvSeries.setAdapter(new SeriesAdapter(arg0));
					if(setSelectionDelay==true){//第一次进来设置历史记录
						gvSeries.setSelection(getHistoryIndex()%PSIZE);
						setSelectionDelay=false;
					}
				}
				mSeriesSet.changePage(arg0);
				if(((GridView)views[arg0]).getTag()!=null){
					Object object=((GridView)views[arg0]).getTag();
					((GridView)views[arg0]).setSelection((Integer) object);
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		//刚进来时的UI初始化
		//默认第一页数据为已请求状态
		mDemandProgram.updateIndex[0]=1;
		mSeriesSet.setItemNum(viewsize,SeriesTotal);
		mSeriesSet.setItemChangedListner(new ItemChangedListner() {
			
			@Override
			public void ItemChanged(int index) {
				viewPager.setCurrentItem(index);
			}
		});
		gvSeries= (GridView)views[getHistoryIndex()/PSIZE];
		gvSeries.setAdapter(new SeriesAdapter(getHistoryIndex()/PSIZE));
		//如果有历史则定位到历史记录
		if(mHistory_episode>0){
			//寻找历史记录在第几个位置
			int index=getHistoryIndex();
			//没找到历史记录.如后台数据更新会出现此情况
			if(index==0){
				noHistoryUiInit();
			}else{
				if(index/PSIZE>0){//非第一页,需要重新请求播放串等数据
					setSelectionDelay=true;
				}else if(index/PSIZE==0){//第一页
					gvSeries.setSelection(index);
				}else{//异常，正常情况下不会出现此情况
					WLog.e(TAG, "诡异的异常");
					index=0;
				}
				viewPager.setCurrentItem(index/PSIZE);
				mSeriesSet.setItemSelected(index/PSIZE);
			}
		}else{//没有历史记录
			noHistoryUiInit();
		}
		//dialog自动消失定时开始
		handler.postDelayed(dismissRunnable,5000);
	}
	private int getHistoryIndex(){
		ArrayList<Integer>seriesList=mDemandProgram.getDetailSeriesSet().getSerieslist();
		int index=0;
		for(index=0;index<seriesList.size();index++){
			if(mHistory_episode==seriesList.get(index)){
				return index;
			}
		}
		return 0;
	}
	private void noHistoryUiInit(){
		viewPager.setCurrentItem(0);
		gvSeries.setSelection(0);
		mSeriesSet.setItemSelected(0);
	}
	Dialog dialog;
	private Runnable dismissRunnable=new Runnable() {
		
		@Override
		public void run() {
			if(dialog!=null&&dialog.isShowing()){
				try {
					dialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};
	Handler handler=new Handler();
	public void setDialog(Dialog dialog){
		this.dialog=dialog;
	}
	//设置选集dialog自动消失
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		handler.removeCallbacks(dismissRunnable);
		handler.postDelayed(dismissRunnable,5000);
		return super.dispatchKeyEvent(event);
	}
	protected void loadSeriesInfo(final int arg0) {
		final String url=mDemandProgram.getDetailUrl()+"&page="+(arg0+1)+"&psize="+PSIZE;
		final ObjectListener objectListener = new ObjectListener() {
			@Override
			public void onObjectGet(int retcode, String extraMsg,
					ObjectBase data) {
				WLog.i(TAG, "arg0="+arg0+",retcode="+retcode);
				//加载数据失败，重新加载
				if (retcode == WError.ERROR_INVALID_DATA|| retcode == WError.ERROR_NET) {
					if (fetchDataRetryCount > 0) {
						DataFetchModule.getInstance().fetchObjectGet(url, DemandProgram.class, this);
						fetchDataRetryCount--;
						return;
					}
				}
				if (retcode != WError.ERROR_NONE) {
					views[arg0].setVisibility(View.VISIBLE);
				}else{
					gvSeries	 = (GridView) views[arg0];
					gvSeries.setAdapter(new SeriesAdapter(arg0));
					if(setSelectionDelay==true){//第一次进来设置历史记录
						gvSeries.setSelection(getHistoryIndex()%PSIZE);
						setSelectionDelay=false;
					}
					views[arg0].setVisibility(View.VISIBLE);
					fetchDataRetryCount = 3;
					mDemandProgram.addPlaySeriesInfo((DemandProgram) data);
					mDemandProgram.updateIndex[arg0]=1;
				}
			}
		};
		WLog.i(TAG, "url=" + url);
		DataFetchModule.getInstance().fetchObjectGet(url,DemandProgram.class, objectListener);
	}
	/**
	 * ViewPager 滚动速度设置
	 * 
	 */
	public class ViewPagerScroller extends Scroller {
	    private int mScrollDuration = 2000;             // 滑动速度
	 
	    /**
	     * 设置速度速度
	     * @param duration
	     */
	    public void setScrollDuration(int duration){
	        this.mScrollDuration = duration;
	    }
	     
	    public ViewPagerScroller(Context context) {
	        super(context);
	    }
	 
	    public ViewPagerScroller(Context context, Interpolator interpolator) {
	        super(context, interpolator);
	    }
	 
	    public ViewPagerScroller(Context context, Interpolator interpolator, boolean flywheel) {
	        super(context, interpolator, flywheel);
	    }
	 
	    @Override
	    public void startScroll(int startX, int startY, int dx, int dy, int duration) {
	        super.startScroll(startX, startY, dx, dy, mScrollDuration);
	    }
	 
	    @Override
	    public void startScroll(int startX, int startY, int dx, int dy) {
	        super.startScroll(startX, startY, dx, dy, mScrollDuration);
	    }
	 
	     
	     
	    public void initViewPagerScroll(ViewPager viewPager) {
	        try {
	            Field mScroller = ViewPager.class.getDeclaredField("mScroller");
	            mScroller.setAccessible(true);
	            mScroller.set(viewPager, this);
	        } catch(Exception e) {
	            e.printStackTrace();
	        }
	    }
	}
	private class SeriesAdapter extends BaseAdapter{
		int index;
		public SeriesAdapter(int arg0){
			index=arg0;
		}
		@Override
		public int getCount() {
			int len=SeriesTotal-index*PSIZE;
			if(len>PSIZE){
				return PSIZE;
			}else{
				return SeriesTotal-index*PSIZE;
			}
		}

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

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tvSeries=null;
			TextView updateTextView;
			if (convertView == null){
				convertView=LayoutInflater.from(getContext()).inflate(R.layout.item_detail_series, null);
			}
			tvSeries =(TextView)convertView.findViewById(R.id.item_series_num);
			ArrayList<Integer> series=mDemandProgram.getDetailSeriesSet().getSerieslist();
			int Seriesnum=series.get(index*PSIZE+position);
			tvSeries.setText(Seriesnum+"");
			updateTextView =(TextView)convertView.findViewById(R.id.item_series_update);
			if(mDemandProgram.isNewUpdate(Integer.parseInt(tvSeries.getText().toString()))){
				updateTextView.setVisibility(View.VISIBLE);
			}else{
				updateTextView.setVisibility(View.INVISIBLE);
			}
			return convertView;
		}
	}
}
