package com.wasu.cs.ui;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.comp.videoview.IMediaListener;
import com.wasu.cs.Statistics.StatisitcsOberserver;
import com.wasu.cs.Statistics.StatisticsOberserverInterface;
import com.wasu.cs.adapter.ContAdapter;
import com.wasu.cs.model.FilmSpecialModel;
import com.wasu.cs.model.IAssetList;
import com.wasu.cs.protocol.FilmSpecialProtocol;
import com.wasu.cs.protocol.FilmSpecialProtocol.FilmSpecialFetchCallback;
import com.wasu.cs.widget.ShortVideoSpecialItem;
import com.wasu.cs.widget.SpecialListView;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.cs.widget.videoview.WasuPlayerView.OnPlayIndexChangedListener;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.log.WLog;
import com.wasu.util.StringUtils;

import org.json.JSONException;
import org.json.JSONStringer;

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

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

/**
 * 
 * @ClassName: ActivityShortVideoSpecial
 * @Description: 短视频专题
 * @author 海迪
 * @date 2015年7月22日 下午3:35:10
 * 
 */
public class ActivityShortVideoSpecial extends ActivityBase implements Runnable, StatisticsOberserverInterface {
	private String TAG = "ActivityShortVideoSpecial";
	private Context context;

	public static int itemHeight = 122;

	private SimpleDraweeView svsBg;
	private SpecialListView listView;
	private SimpleDraweeView winImgView;
	// private ImageView focusImgView;
	private RelativeLayout focusBox, videoBox;
	private SimpleDraweeView statusIconView;
	private WasuPlayerView mVideoView;
	// private RelativeLayout svsBox;
	private ScrollView listSv;
	private View listSvCont;
	private ContAdapter adapter;

	private List<FilmSpecialModel> shortVideoList = new ArrayList<FilmSpecialModel>();

	private String bgImg;
	private String winImgUrl;
	private int winType;
	private String jsonUrl = null;

	@Override
	protected void doCreate(Bundle savedInstanceState) {
		WLog.i(TAG,"doCreate()");

		setContentView(R.layout.activity_short_video_special);
		context = this;
		jsonUrl = getIntent().getStringExtra(IntentConstant.DATAURI.value());
		reqLabelAreaData();
	}

	/**
	 * 
	 * @author 海迪
	 * @Title: reqLabelAreaData
	 * @Description: 向后台请求数据， 成功后，初始化Activity
	 * @param
	 * @return void
	 * @throws
	 * 
	 */
	private void reqLabelAreaData() {
		if (jsonUrl == null || StringUtils.isBlank(jsonUrl)) {
			finish();
		} else {
			jsonUrl = jsonUrl.trim() + "&page=1&psize=200";
		}

		showLoading();
		FilmSpecialProtocol.fetch(jsonUrl, new FilmSpecialFetchCallback() {

			@Override
			public void onResult(boolean successed, FilmSpecialProtocol filmSpecialProtocol) {
				hideLoading();

				if (successed) {
					List<FilmSpecialModel> fsList = filmSpecialProtocol.getFilmSpecialList();

					if (fsList != null) {
						shortVideoList.addAll(fsList);
					}

					bgImg = filmSpecialProtocol.getBgImage();

					winType = filmSpecialProtocol.getWinType();
					if (winType == 1) {

					} else {
						winImgUrl = filmSpecialProtocol.getCoverPicUrl();
						if (StringUtils.isBlank(winImgUrl) && fsList.size() > 0) {
							winImgUrl = fsList.get(0).getPicUrl();
						}
					}

					init();
				} else {

					if (filmSpecialProtocol != null) {
						showErrorExitDlg(ErrorMap.mapError(context, filmSpecialProtocol.getCode(), filmSpecialProtocol.getMessage()));
					} else {
						showErrorExitDlg(getResources().getString(R.string.error_unknown));
					}

				}
			}
		});
	}

	ShortVideoSpecialItem firstListItem;

	/**
	 * 
	 * @author 海迪
	 * @Title: init
	 * @Description: 初始化Activity
	 * @param
	 * @return void
	 * @throws
	 * 
	 */
	private void init() {

		listSv = (ScrollView) findViewById(R.id.list_sv);
		listSvCont = findViewById(R.id.list_sv_cont);

		if (!StringUtils.isBlank(bgImg)) {
			svsBg = (SimpleDraweeView) findViewById(R.id.svs_bg);
			FrescoImageFetcherModule.getInstance().attachImage(bgImg, svsBg);
		}

		listView = (SpecialListView) findViewById(R.id.h_list_view);
		winImgView = (SimpleDraweeView) findViewById(R.id.win_img);
		focusBox = (RelativeLayout) findViewById(R.id.focus_box);

		if (winType == 1) {

			// svsBox = (RelativeLayout) findViewById(R.id.svs_box);
			// focusImgView = (ImageView) findViewById(R.id.focus_img);
			statusIconView = (SimpleDraweeView) findViewById(R.id.cont_status_icon);
			videoBox = (RelativeLayout) findViewById(R.id.videoBox);
			videoBox.setVisibility(View.VISIBLE);
			statusIconView.setVisibility(View.VISIBLE);

			mVideoView = new WasuPlayerView(context, "");
			mVideoView.setExcludeOption(MediaController.DISPLAY_PROMPT_EXIT_AD);
			mVideoView.addObserver(new StatisitcsOberserver(this,mVideoView));
			mVideoView.setAnchorView(videoBox, this);
			videoBox.setClickable(true);
			videoBox.setFocusable(true);
			videoBox.requestFocus();
			mVideoView.addOnPlayIndexChangedListener(new OnPlayIndexChangedListener() {

				@Override
				public void onPlayIndexChanged(int index ,int positon ,int total) {
					Log.d("echo", "当前播到第几个" + index);

				}
			});
			videoBox.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						focusBox.setBackgroundResource(R.drawable.main_page_item_selected);
					} else {

						focusBox.setBackgroundResource(0);
					}

				}
			});
			focusBox.setBackgroundResource(R.drawable.main_page_item_selected);

			videoBox.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (winType == 1) {
						if (mVideoView != null) {
							mVideoView.toggleFullScreen();
						}
					}

				}
			});

		}

		adapter = new ContAdapter(shortVideoList);
		adapter.setViewInterface(new ContAdapter.ViewInterface() {

			@Override
			public View getView(int position, Object dataObject, View convertView, ViewGroup parent) {
				FilmSpecialModel cm = (FilmSpecialModel) dataObject;

				ShortVideoSpecialItem svsItem = null;
				if (convertView == null) {
					svsItem = new ShortVideoSpecialItem(context);
				} else {
					svsItem = (ShortVideoSpecialItem) convertView;
				}

				svsItem.setPosition(position);
				svsItem.setSpecialListView(listView);
				svsItem.initData(cm);

				try {
					JSONStringer js = new JSONStringer();
					js.object();
					js.key("playIndex").value(position);
					js.key("jsonUrl").value(jsonUrl);
					js.endObject();

					svsItem.setTag(js.toString());
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (position == 0) {
					firstListItem = svsItem;
				}
				return svsItem;
			}
		});

		listView.setAdapter(adapter);
		listView.setOnItemSelectedListener(new SpecialListView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(View view, int position) {
				String url = shortVideoList.get(position).getPicUrl();
				if (winType != 1) {

					if (!StringUtils.isBlank(url)) {
						if (winType != 1) {
							winImgView.setVisibility(View.VISIBLE);
							FrescoImageFetcherModule.getInstance().attachImage(url, winImgView, getResources().getDimensionPixelSize(R.dimen.d_8dp));

						}
					}
				}
				if (position > 0) {
					listSv.smoothScrollTo(0, position * AppUtil.getProRataH(context, itemHeight));
				} else {
					listSv.smoothScrollTo(0, 0);
				}
			}
		});
		if (winType != 1) {
			if (!StringUtils.isBlank(winImgUrl)) {
				winImgView.setVisibility(View.VISIBLE);

				FrescoImageFetcherModule.getInstance().attachImage(winImgUrl, winImgView, getResources().getDimensionPixelSize(R.dimen.d_8dp));
			}
		}
		int row = shortVideoList.size();

		if (row > 0) {
			LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) listSvCont.getLayoutParams();
			layoutParams.height = AppUtil.getProRataH(context, itemHeight) * row + AppUtil.getProRataH(context, 650);
			listSvCont.setLayoutParams(layoutParams);
		}

		listSv.setFocusable(false);
		listSvCont.setFocusable(false);
		listView.setVisibility(View.VISIBLE);
		if (mVideoView != null) {
			videoBox.requestFocus();

			setDataAndPlay();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (listView != null) {
			if (listView.hasFocus()) {
				listView.onKeyDown(keyCode, event);
			}
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void finish() {
		if (mVideoView != null)
			mVideoView.stopPlayback();
		super.finish();
	}

	public void setDataAndPlay() {
		PlayerParams playerParams = new PlayerParams();
		playerParams.setAssetList(new IAssetList() {

			@Override
			public int getSize() {
				return shortVideoList.size();
			}

			@Override
			public int getRealSize() {
				return shortVideoList.size();
			}

			@Override
			public String getJsonUrl(int index) {
				return shortVideoList.get(index).getJsonUrl();
			}

			@Override
			public void append(IAssetList assetList) {

			}

			@Override
			public String getPoint(int index) {
				return shortVideoList.get(index).getPoints();
			}

			@Override
			public String getTitle(int index) {
				return shortVideoList.get(index).getTitle();
			}

			@Override
			public String getPicUrl(int index) {
				return shortVideoList.get(index).getPicUrl();
			}
		});
		playerParams.setPlayType(WasuPlayerView.PLAY_TYPE_LOOP);
		playerParams.setPlayIndex(0);
		mVideoView.play(playerParams);

	}

	@Override
	public void onAdStatusChanged(int arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCompletion(MediaPlayer arg0) {

	}

	@Override
	public void onError(MediaPlayer arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInfo(MediaPlayer arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPause(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPrepareComplete(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPreparing(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProgress(int arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onResume(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSeekComplete(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSeeking(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStart(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(MediaPlayer arg0, int arg1) {
		if (IMediaListener.STATE_PLAYING == arg1) {
			statusIconView.setVisibility(View.GONE);
			// iconBox.setVisibility(View.GONE);
		}
	}

	@Override
	public void onStop(MediaPlayer arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onWasuError(int arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onWasuPlayLimit(int arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

	}

}
