package com.wasu.cs.widget;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

import com.wasu.comp.videoview.IMediaListener;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.HomeColumnModel;
import com.wasu.cs.model.SpecialColumnModel.VideoModel;
import com.wasu.cs.model.Swith2DemandPrograme;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.module.msgqueue.MsgHandler;
import com.wasu.module.msgqueue.MsgIdConstant;
import com.wasu.module.msgqueue.MsgQueueModule;

//import android.widget.VideoView;

/**
 * 
 * @ClassName: MainHPageItem22
 * @Description: 内容区视频播放小窗口的Item
 * @author 海迪
 * @date 2015年7月8日 下午6:26:55
 * 
 */
public class MainHPageItemVideoVOD extends MainHPageItemBase implements Runnable, IMediaListener, MsgHandler {

	private static final int ACTION_IDLE = 1 << 0;
	private static final int ACTION_PLAY = 1 << 1;
	private static final int ACTION_PREPARE = 1 << 2;
	private static final int ACTION_PAUSE = 1 << 3;
	private static final int ACTION_RESUME = 1 << 4;
	private static final int ACTION_STOP = 1 << 5;
	private static final int ACTION_SUSPEND = 1 << 6;
	private static final int ACTION_VIDEO_RESUME = 1 << 7;
	private String layout;
	private String jsonUrl;

	private String firstImgUrl;

	private RelativeLayout mContainer;
	// private ImageView mIconPlay = null;
	// private ImageView contFirstImgView;
	private WasuPlayerView mVideoView;

	private ArrayList<VideoModel> videoSourceList = null;
	private int mCurrentStatus = ACTION_IDLE;
	private int mTargetStatus = ACTION_IDLE;
	private Activity context;
	private int linkType;

	private DemandProgram mDemandProgram;

	public MainHPageItemVideoVOD(Activity context) {
		super(context);
		this.context = context;
		init(context);
	}

	Handler handler = new Handler();

	Runnable runnable = new Runnable() {
		@Override
		public void run() {

			MainHPageItemVideoVOD.this.requestFocus();

		}
	};

	private void initVideo() {
		mVideoView = new WasuPlayerView(context, "");
		mVideoView.setExcludeOption(MediaController.DISPLAY_PROMPT_EXIT_AD);
		mVideoView.addObserver(this);
		mVideoView.setAnchorView(this, this.context);

	}

	@SuppressLint("NewApi")
	private void init(Context context) {
		LayoutInflater.from(context).inflate(R.layout.main_hpage_item_video, this);
		int w = getResources().getDimensionPixelSize(R.dimen.d_422dp);
		int h = getResources().getDimensionPixelSize(R.dimen.d_270dp);
		setLayoutParams(new LayoutParams(w, h));
		mContainer = (RelativeLayout) findViewById(R.id.item_box);
		mContainer.setBackgroundColor(Color.TRANSPARENT);

		initVideo();

		MsgQueueModule.getInstance().addMsgHandler(MsgIdConstant.MSGID_APP_MIN + 1, this);
	}

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

		} else if (linkType == 21 || linkType == 22) {// 跳转到layout对应界面

			IntentMap.startIntent(getContext(), null, getLayout(), getJsonUrl(), null);
		}

	}

	@Override
	protected void onWindowVisibilityChanged(int visibility) {
		super.onWindowVisibilityChanged(visibility);
		if (ACTION_IDLE == mCurrentStatus) {
			return;
		}

		if (View.VISIBLE == visibility) {

			if (ACTION_SUSPEND == mCurrentStatus) {// 如果播放器已经release
				mTargetStatus = ACTION_VIDEO_RESUME;
				post(this);
			}
		} else {
			mTargetStatus = ACTION_SUSPEND;
			post(this);
		}

	}

	/**
	 * 改变播放状态
	 * 
	 * @param isChange
	 */
	public void changeStatus(boolean isChange) {

		if (ACTION_IDLE == mCurrentStatus) {
			return;
		}

		if (isChange) {
			// handler1.postDelayed(runnable1, 200);
			resumePlay();
		} else {
			mTargetStatus = ACTION_SUSPEND;
			post(this);

		}
	}

	Handler handler1 = new Handler();
	Runnable runnable1 = new Runnable() {

		@Override
		public void run() {

			resumePlay();
		}
	};

	private void resumePlay() {
		if (ACTION_SUSPEND == mCurrentStatus) {// 如果播放器已经release
			mTargetStatus = ACTION_VIDEO_RESUME;
			post(this);
			return;
		}
		if (mCurrentStatus == ACTION_PAUSE) {
			mTargetStatus = ACTION_RESUME;
			post(this);
		}

	}

	/**
	 * 检测视频窗口被覆盖并处理
	 */
	public void detect() {
		changeStatus(!isCover());
	}

	@Override
	public void focusChange(View v, boolean hasFocus) {
		if (hasFocus) {
			setBackgroundResource(R.drawable.tv_select_focus);
			if (mVideoView != null) {
				if (ACTION_IDLE == mCurrentStatus) {
					mTargetStatus = ACTION_PLAY;
					post(this);
				}
			}

		} else {
			setBackgroundResource(0);
			if (mVideoView != null) {
				if (ACTION_IDLE == mCurrentStatus) {
					mTargetStatus = ACTION_IDLE;
				}
			} else if (ACTION_PREPARE == mCurrentStatus) {
				mTargetStatus = ACTION_PAUSE;
			}
		}
	}

	@Override
	public String getLayout() {
		return layout;
	}

	@Override
	public String getJsonUrl() {
		return jsonUrl;
	}

	@Override
	public int getRowspan() { // 行
		return 2;
	}

	@Override
	public int getColspan() { // 列
		return 2;
	}

	@Override
	public boolean isFrontItem() {
		return false;
	}

	@Override
	public boolean isVideoItem() {
		return true;
	}

	private HomeColumnModel cm;

	@Override
	public HomeColumnModel getData() {
		return cm;
	}

	@Override
	public void initData(HomeColumnModel cm) {
		this.cm = cm;
		this.linkType = cm.getLinkType();

		layout = cm.getLayout();
		jsonUrl = cm.getJsonUrl();
		if (cm.getPicUrlList().size() > 0) {
			firstImgUrl = cm.getPicUrlList().get(0).getBottomPic();
		}
		// cm.getParentLayout()
		// cm.get

		// playUrl=cm.getJsonUrl();

		videoSourceList = cm.getVideoSourceList();
		mDemandProgram = Swith2DemandPrograme.VideoModel2DemandPrograme(videoSourceList);

	}

	// private String getPlayUrl(int rate) {
	// if (videoSourceList == null || videoSourceList.isEmpty()) {
	// return null;
	// }
	// for (int i = 0; i < videoSourceList.size(); i++) {
	// if (videoSourceList.get(i).getRate() == rate) {
	// return videoSourceList.get(i).getPlayUrls().get(0);
	// }
	// }
	//
	// return videoSourceList.get(0).getPlayUrls().get(0);
	//
	// // return null;
	// }

	// String playUrl;

	@Override
	public void run() {
		if (mVideoView == null) {
			return;
		}

		if (ACTION_PLAY == mTargetStatus) {
			mTargetStatus = ACTION_IDLE;
			// playUrl = getPlayUrl(640000);
			if (TextUtils.isEmpty(cm.getJsonUrl())) {
				return;
			}
			// playUrl =

			// "55FCDB38CF49A36834E22C3B83302121BF0C5E1CA4CBF9C894BB4110BD532A81558E4DEA2BCDF4D0C5440FA715B86D0ED1BACAC18B90AF1DD76D6730F7AB522F3E21FBD6050D9D479E6554BF92D28ADBF420D7BB7839C78A4DFEDC89FD2C61FD7ACC5C80135E646B758FA4C75E22D4E0FC0F9402FDCD17BF33C7993C534E90E63A62A22E3739964B82766674875D77774BA4DAE8A37343CF874FD3358BD476F081ACC1B95D1E17854F457CCE2AB83A26836D6483C66618B23F75E7C17212FEF3";
			//
			if (!isCover()) {
				try {

					PlayerParams playerParams = new PlayerParams();
					playerParams.setAssetInfo(mDemandProgram);
					playerParams.setPlayType(WasuPlayerView.PLAY_TYPE_NORMAL);
					mVideoView.play(playerParams);

					// mVideoView.setVideoPath(playUrl, new UrlProperty());
					mVideoView.start();
					mCurrentStatus = ACTION_PREPARE;
				} catch (Exception e) {
					Log.d("echo", "无效的播放地址");
					mVideoView = null;
					mCurrentStatus = ACTION_IDLE;
					mTargetStatus = ACTION_IDLE;
				}
			}

		} else if (ACTION_PAUSE == mTargetStatus) {
			if (mVideoView.isPlaying()) {
				mTargetStatus = ACTION_IDLE;
				mCurrentStatus = ACTION_PAUSE;
				mVideoView.pause();

			}
		} else if (ACTION_RESUME == mTargetStatus) {
			mTargetStatus = ACTION_IDLE;
			if (!isCover()) {
				Log.d("echo", "ACTION_RESUMEcg");
				mVideoView.start();
				mCurrentStatus = ACTION_PLAY;
			}
		} else if (ACTION_STOP == mTargetStatus) {
			mCurrentStatus = ACTION_STOP;
			mTargetStatus = ACTION_IDLE;
			mVideoView.stopPlayback();
		} else if (ACTION_SUSPEND == mTargetStatus) {
			mCurrentStatus = ACTION_SUSPEND;
			mTargetStatus = ACTION_IDLE;
			mVideoView.suspend();
		} else if (ACTION_VIDEO_RESUME == mTargetStatus) {
			mTargetStatus = ACTION_IDLE;
			if (!isCover()) {// 如果没被盖住
				try {
					mVideoView.resume(null);
					mCurrentStatus = ACTION_PREPARE;
				} catch (Exception e) {
					Log.d("echo", "无效的播放地址");
					mCurrentStatus = ACTION_SUSPEND;
				}

			}
		}
	}

	@Override
	public void onWasuPlayLimit(int arg0, String arg1) {
	}

	@Override
	public void onWasuError(int arg0, String arg1) {
	}

	@Override
	public void onStop(MediaPlayer arg0) {
	}

	@Override
	public void onStatusChanged(MediaPlayer arg0, int arg1) {
		if (IMediaListener.STATE_PLAYING == arg1) {
		}
	}

	@Override
	public void onStart(MediaPlayer arg0) {
	}

	@Override
	public void onSeeking(MediaPlayer arg0) {
	}

	@Override
	public void onSeekComplete(MediaPlayer arg0) {
	}

	@Override
	public void onResume(MediaPlayer arg0) {
	}

	@Override
	public void onProgress(int arg0, int arg1, int arg2) {
		// mCurrentPostion = arg0;
	}

	@Override
	public void onPreparing(MediaPlayer arg0) {
	}

	@Override
	public void onPrepareComplete(MediaPlayer arg0) {
		if (mVideoView == null)
			return;
		if (ACTION_PAUSE == mTargetStatus) {
			post(this);
			return;
		}

		if (ACTION_PREPARE == mCurrentStatus) {
			mCurrentStatus = ACTION_PLAY;
			mVideoView.start();
			return;
		}
	}

	@Override
	public void onPause(MediaPlayer arg0) {
	}

	@Override
	public void onInfo(MediaPlayer arg0, int arg1, int arg2) {
	}

	@Override
	public void onError(MediaPlayer arg0, int arg1, int arg2) {
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {

		// mCurrentPostion = 0;

		mTargetStatus = ACTION_PLAY;
		post(MainHPageItemVideoVOD.this);
	}

	@Override
	public void onAdStatusChanged(int arg0, int arg1) {
	}

	@Override
	public boolean handleMsg(int arg0, int arg1, String arg2, Object arg3) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isAliRecItem() {

		return false;
	}

	@Override
	public void notifyPlay(boolean isToPlay) {
		if (isToPlay) {
			mTargetStatus = ACTION_VIDEO_RESUME;
			post(this);
		} else {
			mTargetStatus = ACTION_SUSPEND;
			post(this);
		}

	}

}
