package com.wasu.cs.widget.mediacontrol;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wasu.common.WError;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.DetailSeriesSet;
import com.wasu.cs.ui.ActivityPlayer;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.module.datafetch.DataFetchListener.ObjectListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;

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

import cn.com.wasu.main.R;

public class RecommendTVPanel extends LinearLayout implements OnPageChangeListener, OnItemSelectedListener, OnFocusChangeListener {

	private MediaController mediaController;

	private ViewPager tvSeries;
	private LinearLayout seriesIndicator;

	private TvServiesAdapter mAdapter;

	private int indiIndex;

	public RecommendTVPanel(Context context) {
		super(context);

		init();
	}

	private void init() {
		setOrientation(VERTICAL);
		setBackgroundResource(R.color.prompt_footer_tv_bg);
		setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.d_174dp));
		setLayoutParams(lp);
		setPadding(getResources().getDimensionPixelSize(R.dimen.d_140dp), 0, getResources().getDimensionPixelSize(R.dimen.d_140dp), 0);

		tvSeries = new ViewPager(getContext());
		tvSeries.setOffscreenPageLimit(2);
		tvSeries.setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
		tvSeries.setPadding(0, getResources().getDimensionPixelSize(R.dimen.d_10dp), 0, getResources().getDimensionPixelSize(R.dimen.d_10dp));
		tvSeries.addOnPageChangeListener(this);
		LinearLayout.LayoutParams tvSeriesLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.d_114dp));
		tvSeries.setLayoutParams(tvSeriesLp);

		mAdapter = new TvServiesAdapter();
		tvSeries.setAdapter(mAdapter);

		addView(tvSeries);

		View divider = new View(getContext());
		divider.setFocusable(false);
		divider.setFocusableInTouchMode(false);
		LinearLayout.LayoutParams dividerLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.d_1dp));
		divider.setLayoutParams(dividerLp);
		divider.setBackgroundResource(R.color.prompt_footer_tv_l);

		addView(divider);

		HorizontalScrollView scrollView = new HorizontalScrollView(getContext());
		scrollView.setHorizontalScrollBarEnabled(false);
		scrollView.setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
		LinearLayout.LayoutParams scrollViewLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.d_59dp));
		scrollView.setLayoutParams(scrollViewLp);

		seriesIndicator = new LinearLayout(getContext());
		seriesIndicator.setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
		seriesIndicator.setOrientation(LinearLayout.HORIZONTAL);
		scrollView.addView(seriesIndicator, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

		addView(scrollView);
	}

	public void attachMediaController(final MediaController mediaController) {
		this.mediaController = mediaController;

        if (mediaController.getAssetInfo().getDetailSeriesSet() == null) {
            DataFetchModule.getInstance().fetchObjectGet(mediaController.getAssetInfo().getOnlineEpisodesUrl(), DetailSeriesSet.class, new ObjectListener() {
                @Override
                public void onObjectGet(int i, String s, ObjectBase objectBase) {
                    if (i == WError.ERROR_NONE) {
                        DetailSeriesSet mDetailSeriesSet = (DetailSeriesSet) objectBase;
                        if (mDetailSeriesSet != null) {
                            mediaController.getAssetInfo().setDetailSeriesSet(mDetailSeriesSet);
                        }
                    }

                    invalidatePagerIndicator();
                    invalidatePager();
                }
            });
        } else {
            invalidatePagerIndicator();
            invalidatePager();
        }

	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (tvSeries.hasFocus()) {
			if(mAdapter.getViewLists()!=null&&mAdapter.getViewLists().get(tvSeries.getCurrentItem())!=null){
				GridView selectedGridView = (GridView) mAdapter.getViewLists().get(tvSeries.getCurrentItem());
				int position = selectedGridView.getSelectedItemPosition();
				int count = selectedGridView.getChildCount();

				if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN && (count <= 15 || (count > 15 && position >= 15))) {
					View v = ((GridView) mAdapter.getViewLists().get(tvSeries.getCurrentItem())).getChildAt(position);
					if (v != null) {
						v.setSelected(false);
					}
					v = seriesIndicator.getChildAt(indiIndex);
					if (v != null) {
						v.requestFocus();
					}
				}

				if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
					View v = selectedGridView.getSelectedView();
					if (v != null) {
						v.performClick();
					}
				}
			}
		} else if (seriesIndicator.hasFocus()) {
            int count = 0;
            if (mediaController != null && mediaController.getAssetInfo() != null) {
                DetailSeriesSet detailSeriesSet = mediaController.getAssetInfo().getDetailSeriesSet();
                if (detailSeriesSet != null) {
                    count = detailSeriesSet.getSize();
                }
            }

			switch (event.getKeyCode()) {
			case KeyEvent.KEYCODE_DPAD_UP:
				tvSeries.requestFocus();
				break;
			case KeyEvent.KEYCODE_DPAD_LEFT:
				if (indiIndex != 0) {
					View v = seriesIndicator.getChildAt(indiIndex - 1);
					if (v != null) {
						v.requestFocus();
					}
				}
				break;
			case KeyEvent.KEYCODE_DPAD_RIGHT:
				if (indiIndex != count) {
					View v = seriesIndicator.getChildAt(indiIndex + 1);
					if (v != null) {
						v.requestFocus();
					}
				}
				break;
			}
		}

		if (seriesIndicator.getChildCount() > 8) {
			if (seriesIndicator.hasFocus()) {
				return true;
			} else {
				return super.dispatchKeyEvent(event);
			}
		} else {
			return super.dispatchKeyEvent(event);
		}
	}

	/**
	 * 刷新pager indicator
	 */
	private void invalidatePagerIndicator() {
		seriesIndicator.removeAllViews();

        DetailSeriesSet detailSeriesSet = mediaController.getAssetInfo().getDetailSeriesSet();
        if (detailSeriesSet == null) {
            return;
        }

        int count = detailSeriesSet.getSize();
        List<Integer> serieslist = detailSeriesSet.getSerieslist();

		for (int i = 0; i < count / 30; i++) {
			TextView t = new TextView(getContext());
			t.setFocusable(true);
			t.setFocusableInTouchMode(true);
			t.setSingleLine(true);
			LinearLayout.LayoutParams tLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			tLp.gravity = Gravity.CENTER_VERTICAL;
			tLp.leftMargin = getResources().getDimensionPixelSize(R.dimen.d_15dp);
			tLp.rightMargin = getResources().getDimensionPixelSize(R.dimen.d_30dp);
			t.setLayoutParams(tLp);

			t.setText(serieslist.get(i * 30) + "-" + serieslist.get((i + 1) * 30 - 1));
			t.setTag(i);
			t.setGravity(Gravity.CENTER);
			t.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.d_22dp));
			t.setTextColor(getResources().getColorStateList(R.color.media_controller_recommend_tv_panel_item_indi_bg));
			t.setBackgroundColor(Color.TRANSPARENT);
			t.setOnFocusChangeListener(this);

			seriesIndicator.addView(t);
		}

		if (count % 30 != 0) {
			TextView t = new TextView(getContext());
			t.setFocusable(true);
			t.setFocusableInTouchMode(true);
			t.setSingleLine(true);
			LinearLayout.LayoutParams tLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			tLp.gravity = Gravity.CENTER_VERTICAL;
			tLp.leftMargin = getResources().getDimensionPixelSize(R.dimen.d_15dp);
			tLp.rightMargin = getResources().getDimensionPixelSize(R.dimen.d_30dp);
			t.setLayoutParams(tLp);

            t.setText(serieslist.get((count / 30) * 30) + "-" + serieslist.get(count - 1));
            t.setTag(count / 30);
			t.setGravity(Gravity.CENTER);
			t.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.d_22dp));
			t.setTextColor(getResources().getColorStateList(R.color.media_controller_recommend_tv_panel_item_indi_bg));
			t.setBackgroundColor(Color.TRANSPARENT);
			t.setOnFocusChangeListener(this);

			seriesIndicator.addView(t);
		}
		
	}
	
	/**
	 * 刷新pager
	 */
	private void invalidatePager() {
		if (mAdapter.getViewLists() != null) {
			mAdapter.getViewLists().clear();
			mAdapter.notifyDataSetChanged();
		}

        DetailSeriesSet detailSeriesSet = mediaController.getAssetInfo().getDetailSeriesSet();
        if (detailSeriesSet == null) {
            return;
        }

        int count = detailSeriesSet.getSize();
        List<Integer> serieslist = detailSeriesSet.getSerieslist();

        List<View> views = new ArrayList<View>();
		for (int i = 0; i < count / 30; i++) {
			SelectedGridView container = new SelectedGridView(getContext());
			container.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
			container.setGravity(Gravity.CENTER);
			container.setNumColumns(15);
			container.setVerticalSpacing(getResources().getDimensionPixelSize(R.dimen.d_14dp));
			container.setSelector(new ColorDrawable(Color.TRANSPARENT));
			container.setAdapter(new TvSeriesItemAdapter(30, i));
			container.setOnItemSelectedListener(this);
			container.setTag(false);

			views.add(container);
		}

		if (count % 30 != 0) {
			SelectedGridView container = new SelectedGridView(getContext());
			container.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
			container.setGravity(Gravity.CENTER);
			container.setNumColumns(15);
			container.setVerticalSpacing(getResources().getDimensionPixelSize(R.dimen.d_14dp));
			container.setSelector(new ColorDrawable(Color.TRANSPARENT));

            int start = (count / 30) * 30;

			container.setAdapter(new TvSeriesItemAdapter(count % 30, count / 30, start));
            container.setOnItemSelectedListener(this);
            container.setTag(false);

			views.add(container);
		}

		mAdapter.setViewLists(views);
		mAdapter.notifyDataSetChanged();

        for (int i = 0; i < serieslist.size(); i++) {
            if (mediaController.getAssetInfo().getCurPlayIndex() == serieslist.get(i)) {
                int curItem = i / 30;
                tvSeries.setCurrentItem(curItem);
                onPageSelected(curItem);
                break;
            }
        }

        final GridView selectedGrid = ((GridView) views.get(tvSeries.getCurrentItem()));
        selectedGrid.post(new Runnable() {
            @Override
            public void run() {
				if(mediaController == null){
					return;
				}
				if(mediaController.getAssetInfo() == null){
					return;
				}
				int childCount = selectedGrid.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    View v = selectedGrid.getChildAt(i);
                    if (v != null && v.getTag() != null) {
                        int pos = (Integer) v.getTag();
                        if (pos == mediaController.getAssetInfo().getCurPlayIndex()) {
                            selectedGrid.setSelection(i);
                            /*if (i == 0) {
                                View view = selectedGrid.getChildAt(i);
                                if (view != null) {
                                    view.setSelected(true);
                                    view.requestFocus();
                                }
                            }*/
                            break;
                        }
                    }
                }
            }
        });
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int arg0) {
		indiIndex = arg0;

		for (int i = 0; i < seriesIndicator.getChildCount(); i++) {
			TextView t = (TextView) seriesIndicator.getChildAt(i);
			t.setCompoundDrawables(null, null, null, null);
			t.setTextColor(getResources().getColor(R.color.prompt_footer_tv_l));
		}

		final TextView t = (TextView) seriesIndicator.getChildAt(arg0);
		if (t != null) {
			final ColorDrawable cd = new ColorDrawable(Color.WHITE);
			t.post(new Runnable() {
				@Override
				public void run() {
					cd.setBounds(0, 0, t.getMeasuredWidth(), getResources().getDimensionPixelSize(R.dimen.d_2dp));
					t.setCompoundDrawables(null, null, null, cd);
				}
			});
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		indiIndex = (Integer) v.getTag();
		tvSeries.setCurrentItem(indiIndex);

		if (hasFocus) {
			((TextView) v).setTextColor(getResources().getColor(R.color.prompt_footer_tv_h));
		} else {
			((TextView) v).setTextColor(getResources().getColor(R.color.prompt_footer_tv_l));
		}
	}

	class TvServiesAdapter extends PagerAdapter {

		private List<View> viewLists;

		public List<View> getViewLists() {
			return viewLists;
		}

		public void setViewLists(List<View> viewLists) {
			this.viewLists = viewLists;
		}
		
		@Override
		public int getCount() {
			if (viewLists == null) {
				return 0;
			}

			return viewLists.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			if (!(Boolean) viewLists.get(position).getTag() && mediaController != null) {
				final DemandProgram assetInfo = mediaController.getAssetInfo();
				
				if (assetInfo != null && !TextUtils.isEmpty(assetInfo.getDetailUrl())) {
					String url = assetInfo.getDetailUrl() + "&page=" + (position + 1) + "&psize=30";
					DataFetchModule.getInstance().fetchObjectGet(url, DemandProgram.class, new ObjectListener() {
						@Override
						public void onObjectGet(int retcode, String extraMsg, ObjectBase data) {
							if (retcode == WError.ERROR_NONE) {
								assetInfo.addPlaySeriesInfo((DemandProgram) data);
								viewLists.get(position).setTag(true);
							}
						}
					});
				}
			}
			
			container.addView(viewLists.get(position));
			return viewLists.get(position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(viewLists.get(position));
		}

	}

	class TvSeriesItemAdapter extends BaseAdapter {

		private int count;
		private int index;
        private int start;

        List<Integer> serieslist = new ArrayList<Integer>();

        public TvSeriesItemAdapter(int count, int index) {
			this(count, index, -1);
		}

        public TvSeriesItemAdapter(int count, int index, int start) {
            this.count = count;
            this.index = index;
            this.start = start;

            DetailSeriesSet detailSeriesSet = mediaController.getAssetInfo().getDetailSeriesSet();
            if (detailSeriesSet != null) {
                serieslist.addAll(detailSeriesSet.getSerieslist());
            }
        }

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = new TextView(getContext());
                convertView.setFocusable(true);
                convertView.setBackgroundResource(R.drawable.media_controller_recommend_tv_panel_selector);
            }
			convertView.setClickable(true);
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
                    int pos = (Integer) v.getTag();
					if (pos == mediaController.getAssetInfo().getCurPlayIndex()) {
						return;
					}
					
					mediaController.getPlayer().stopPlayback();
					mediaController.post(new Runnable() {

						@Override
						public void run() {
							mediaController.hideCurrentView();
						}
						
					});
					
					if (getContext() instanceof ActivityPlayer) {
						Intent intent = new Intent(ActivityPlayer.ACTION);
						mediaController.getAssetInfo().setCurPlayIndex(pos);
						intent.putExtra(ActivityPlayer.ASSET_INFO, mediaController.getAssetInfo());
						mediaController.getContext().startActivity(intent);
					} else {
						PlayerParams playerParams = mediaController.getPlayerParams();
						if (playerParams == null || (playerParams != null && playerParams.getPlayType() == WasuPlayerView.PLAY_TYPE_NORMAL)) {
							playerParams = new PlayerParams();
							mediaController.getAssetInfo().setCurPlayIndex(pos);
							playerParams.setAssetInfo(mediaController.getAssetInfo());
							((WasuPlayerView) mediaController.getPlayer()).play(playerParams);
							return;
						}

						mediaController.getAssetInfo().setCurPlayIndex(pos);
						playerParams.setAssetInfo(mediaController.getAssetInfo());
						((WasuPlayerView) mediaController.getPlayer()).play(playerParams);
					}
				}
			});
            ViewGroup.LayoutParams tLp = convertView.getLayoutParams();
            if (tLp == null) {
                tLp = new AbsListView.LayoutParams(getResources().getDimensionPixelSize(R.dimen.d_40dp), getResources().getDimensionPixelSize(R.dimen.d_40dp));
            } else {
                tLp.width = getResources().getDimensionPixelSize(R.dimen.d_40dp);
                tLp.height = getResources().getDimensionPixelSize(R.dimen.d_40dp);
            }
			convertView.setLayoutParams(tLp);

            int pos = index * 30 + position;
            if (start != -1) {
                pos = start + position;
            }
            convertView.setTag(serieslist.get(pos));
            ((TextView) convertView).setText(String.valueOf(serieslist.get(pos)));
			((TextView) convertView).setGravity(Gravity.CENTER);
			((TextView) convertView).setSingleLine();
            ((TextView) convertView).setEllipsize(TextUtils.TruncateAt.MARQUEE);
            ((TextView) convertView).setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.d_20dp));
			((TextView) convertView).setTextColor(getResources().getColorStateList(R.color.media_controller_recommend_tv_panel_item_bg));
			((TextView) convertView).setHorizontallyScrolling(true);
			((TextView) convertView).setFreezesText(true);
			return convertView;
		}

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

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

		@Override
		public int getCount() {
			return count;
		}
	}

	class SelectedGridView extends GridView {

		public SelectedGridView(Context context) {
			super(context);
		}

		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if (getSelectedItemPosition() == 15 && keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
				setSelection(14);
				return true;
			}

			if (getSelectedItemPosition() == 14 && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && getCount() > 15) {
				setSelection(15);
				return true;
			}

            if (getSelectedItemPosition() == getCount() - 1 && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && getCount() < 30) {
                return true;
            }

			return super.onKeyDown(keyCode, event);
		}

        @Override
        public boolean isInTouchMode() {
            if (19 == Build.VERSION.SDK_INT) {
                return !(hasFocus() && !super.isInTouchMode());
            } else {
                return super.isInTouchMode();
            }
        }
	}

}
