package com.wasu.cs.widget.mediacontrol;

import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wasu.common.WError;
import com.wasu.cs.model.DemandList;
import com.wasu.cs.model.DemandList.Datum;
import com.wasu.cs.model.IAssetList;
import com.wasu.cs.model.Recommend;
import com.wasu.cs.model.Recommend.RecommendData;
import com.wasu.cs.ui.ActivityPlayer;
import com.wasu.cs.widget.mediacontrol.adapter.RecommendAdapter;
import com.wasu.cs.widget.mediacontrol.adapter.RecommendEntry;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.datafetch.DataFetchListener.ObjectListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

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

public class RecommendVideoClipPanel extends FrameLayout {

	private MediaController mediaController;
	private RecommendContainer container;
	
	private DemandList demandList = new DemandList();

	private IAssetList assetList;
	private String assetUrl;
	
	private void append(Recommend recommend) {
		Datum data = demandList.getDatum();
		
		if (data == null) {
			data = new Datum();
			demandList.setDatum(data);
		}
		
		List<DemandList.Asset> assets = data.getAssets();
		
		if (assets == null) {
			assets = new ArrayList<DemandList.Asset>();
			data.setAssets(assets);
		}
		
		List<RecommendData> l = recommend.getData();
		if (l != null && l.size() != 0) {
			
			for (RecommendData asset : l) {
				DemandList.Asset a = new DemandList.Asset();
				a.setPicUrl(asset.getPicUrl());
				a.setTitle(asset.getTitle());
				a.setSummary(asset.getSummary());
				a.setJsonUrl(asset.getJsonUrl());
				a.setLayout(asset.getLayout());
				
				assets.add(a);
			}
		}
	}

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

		init();
	}

	private void init() {
		setClipChildren(false);
		setClipToPadding(false);
		setBackgroundResource(R.drawable.media_controller_recommend_video_clip_bg);
		setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.d_300dp));
		setLayoutParams(lp);

		container = new RecommendContainer(getContext());
		container.setShowItemCount(4);
		container.setPadding(getResources().getDimensionPixelSize(R.dimen.d_30dp), 0, getResources().getDimensionPixelSize(R.dimen.d_30dp), 0);
		FrameLayout.LayoutParams hLp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.d_225dp));
		hLp.gravity = Gravity.BOTTOM;
		container.setLayoutParams(hLp);

		addView(container);
	}
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		return container.dispatchKeyEvent(event);
	}

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

		invalidateRecommends();
	}

	private void invalidateRecommends() {
		if (mediaController == null || mediaController.getAssetInfo() == null) {
			return;
		}

		assetList = mediaController.getAssetList();
		assetUrl = mediaController.getAssetUrl();
		if (assetList == null) {
			if (mediaController.getPlayerParams() != null) {
				assetList = mediaController.getPlayerParams().getAssetList();
			}
		}

		if (assetList == null) {
			String rcmUrl = mediaController.getAssetInfo().getRecommendUrl() + "&onPlay=" + mediaController.getAssetInfo().getAssetFrom();
			DataFetchModule.getInstance().fetchObjectGet(rcmUrl, Recommend.class, new ObjectListener() {

				@Override
				public void onObjectGet(int arg0, String arg1, ObjectBase arg2) {
					if (arg0 != WError.ERROR_NONE) {
						return;
					}

					Recommend recommend = (Recommend) arg2;
					append(recommend);

					if (recommend == null) {
						return;
					}

					RecommendAdapter adapter = new RecommendAdapter(recommend.getData());
					adapter.setViewInterface(new RecommendAdapter.ViewInterface() {
						@Override
						public View getView(final int position, Object dataObject, View convertView, ViewGroup parent) {
							RecommendData data = (RecommendData) dataObject;
							return generateView(convertView, position, data.getTitle(), data.getPicUrl(), data.getJsonUrl());
						}
					});

					container.setAdapter(adapter);

					if (adapter.getCount() <= container.getShowItemCount()) {
						container.getChildAt(0).requestFocus();
					}else{
						container.getChildAt(1).requestFocus();
					}
				}
			});
		} else {
			post(new Runnable() {
				@Override
				public void run() {
					RecommendAdapter adapter = new RecommendAdapter(RecommendEntry.generateList(assetList));
					adapter.setViewInterface(new RecommendAdapter.ViewInterface() {
						@Override
						public View getView(int position, Object dataObject, View convertView, ViewGroup parent) {
							RecommendEntry entry = (RecommendEntry) dataObject;
							return generateView(convertView, position, entry.getTitle(), entry.getPicUrl(), entry.getJsonUrl());
						}
					});
					container.setAdapter(adapter);

					if (assetList.getSize() <= container.getShowItemCount()) {
						container.getChildAt(0).requestFocus();
					}else{
						container.getChildAt(1).requestFocus();
					}
				}
			});
		}
	}

	private View generateView(View convertView, final int position, String sTitle, String sPicUrl, final String sJsonUrl) {
		View view;
		if (convertView == null) {
			view = LayoutInflater.from(getContext()).inflate(R.layout.media_controller_prompt_footer_video_recommend, null);
		} else {
			view = convertView;
		}

		view.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					v.findViewById(R.id.title).setSelected(true);

					v.setScaleX(1.15f);
					v.setScaleY(1.15f);
					container.setFocusedItemIndex(v);
				} else {
					v.findViewById(R.id.title).setSelected(false);

					v.setScaleX(1.0f);
					v.setScaleY(1.0f);
					container.setFocusedItemIndex(null);
				}
			}
		});
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mediaController.getPlayer().stopPlayback();
				mediaController.post(new Runnable() {

					@Override
					public void run() {
						mediaController.hideCurrentView();
					}

				});

				if (assetList == null) {
					if (getContext() instanceof ActivityPlayer) {
						Intent intent = new Intent(ActivityPlayer.ACTION);
						intent.putExtra(ActivityPlayer.ASSET_URL, sJsonUrl);
						mediaController.getContext().startActivity(intent);
					} else {
						PlayerParams playerParams = new PlayerParams();
						playerParams.setAssetUrl(sJsonUrl);
						((WasuPlayerView) mediaController.getPlayer()).play(playerParams);
					}
				} else {
					if (getContext() instanceof ActivityPlayer) {
						Intent intent = new Intent(ActivityPlayer.ACTION);
						intent.putExtra(ActivityPlayer.PLAY_TYPE, ActivityPlayer.PLAY_TYPE_LOOP);
						intent.putExtra(IntentConstant.PLAY_INDEX.value(), position);
						intent.putExtra(ActivityPlayer.ASSET_LIST, (Serializable) assetList);
						intent.putExtra(ActivityPlayer.ASSET_URL, assetUrl);
						mediaController.getContext().startActivity(intent);
					} else {
						PlayerParams playerParams = new PlayerParams();
						playerParams.setPlayType(WasuPlayerView.PLAY_TYPE_LOOP);
						playerParams.setPlayIndex(position);
						playerParams.setAssetList(assetList);
						playerParams.setAssetUrl(assetUrl);
						((WasuPlayerView) mediaController.getPlayer()).play(playerParams);
					}
				}
			}
		});

		ImageView pic = (ImageView) view.findViewById(R.id.pic);
		TextView title = (TextView) view.findViewById(R.id.title);

		FrescoImageFetcherModule.getInstance().attachImage(sPicUrl, pic, getResources().getDimensionPixelSize(R.dimen.d_10dp));
		title.setText(sTitle);

		return view;
	}

}
