package com.wasu.cs.widget;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wasu.authsdk.AuthSDK;
import com.wasu.cs.Statistics.StatisitcsOberserver;
import com.wasu.cs.Statistics.StatisticsOberserverInterface;
import com.wasu.cs.model.CatData.AssetElement;
import com.wasu.cs.model.CatData.BaseElement;
import com.wasu.cs.model.IAssetList;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.log.WLog;
import com.wasu.statistics.PlayInfo;
import com.wasu.widget.FocusLinearLayout;

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

import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.AppUtil;
import cn.com.wasu.main.R;

/**
 * Created by LiuYang on 7/24/15.
 */
public class ChannelVideoLayout extends RelativeLayout implements IViewItem,
		View.OnClickListener, StatisticsOberserverInterface, WasuPlayerView.OnPlayIndexChangedListener {

	private final static String TAG = ChannelVideoLayout.class.getSimpleName();
	//UI
	private WasuPlayerView mVideoView;
	private TextView mTextView;
	private ImageView mImageView;
	private ImageView mPlayIcon;
	private FocusLinearLayout mFocusLayout;
	private RelativeLayout mVideoLayout;
	//数据
	private BaseElement mData;
	private List<AssetElement> mAssets = new ArrayList<>();
	private int mPlayIndex = -1;/**当前播放的是第几个资产**/
	private boolean mOffscreen = true;
	private Context mContext;
	/**记录集合资产播放的第几集**/
	private int curPlayPosition = 1;
	/**记录是否是用户点击资产list播放的视频**/
	private boolean isPlayedIndex = false;
	/**视频窗口获得焦点调用了palyVideo()方法，但是还没有setData设置数据**/
	private boolean playButDataIsNull = false;
	/**资产的总集数**/
	private int totalCount = 1;
    private boolean isPlayFinished;

	public ChannelVideoLayout(Context context) {
		super(context);
		init(context);
	}

	public ChannelVideoLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public ChannelVideoLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}
	private PlayIndexChangedListener indexChangedListener;
	private void init( Context context) {
		mContext = context;
		LayoutInflater.from(context).inflate(R.layout.item_channel_video_layout, this);
		mTextView = (TextView) findViewById(R.id.name);

		mFocusLayout = (FocusLinearLayout) findViewById(R.id.focusLayout);
		mFocusLayout.setFocusRealId(R.id.imageView);
		mFocusLayout.setFocusHighlightDrawable(R.drawable.tv_select_focus);
		mFocusLayout.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					mOffscreen = false;
					postDelayed(new Runnable() {
						public void run() {
                            if (mOffscreen || isPlayFinished) {
                                isPlayFinished = false;
                                return;
                            }

							initVideoView(getContext());
							mVideoView.setAnchorView(mVideoLayout ,(Activity)mContext);
							if (mVideoView.isPlaying() || mVideoView.isAdPlaying()) {
								return;
							}

							playVideo();
						}
					}, 300);
				}
			}
		});

		mVideoLayout = (RelativeLayout) findViewById(R.id.videoLayout);
		mVideoLayout.setFocusable(true);
		mVideoLayout.setClickable(true);
		mVideoLayout.setOnClickListener(this);
		mVideoLayout.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					mFocusLayout.requestFocus();
				}
			}

		});

		mImageView = (ImageView) findViewById(R.id.imageView);
		mPlayIcon = (ImageView) findViewById(R.id.playIcon);

//		mImageView = (ImageView) findViewById(R.id.imageView);
//		mPlayIcon = (ImageView) findViewById(R.id.playIcon);

	}
	
	private void initVideoView(Context context){
		if(mVideoView == null){
			mVideoView = new WasuPlayerView(context, BuildType.payTypeUrl);
            mVideoView.setExcludeOption(MediaController.DISPLAY_PROMPT_EXIT_AD);
            mVideoView.addObserver(new StatisitcsOberserver(this,mVideoView));

            mVideoView.addOnPlayIndexChangedListener(this);
		}
		if(mVideoView.getParent() == null){  //说明播放器还没有添加到当前的layout
			mVideoView.setAnchorView(mVideoLayout ,(Activity)mContext);
		}
	}
	
	/**
	 * 为视频播放器设置播放index监听器
	 * @param PlayIndexChangedListener
	 * @author Danxx created on 2016/1/11
	 */
	public void setOnPlayIndexChangedListener(PlayIndexChangedListener PlayIndexChangedListener){
		this.indexChangedListener = PlayIndexChangedListener;
	}
	/**
	 * 监听播放器当前播放index接口
	 * @author Danxx created on 2016/1/11
	 *
	 */
	public interface PlayIndexChangedListener{
		public void onCurrentIndex(int index);
		/*当所有的资产播放完成清除“播放中”指示器*/
		public void cleanPlayIndex(int index);
	}
	
	public void removePlayIndexChangedListener(){
		if(indexChangedListener == null){
			return;
		}else{
			indexChangedListener = null;
		}
	}
	
	@Override
	public void finalize() throws Throwable {
		super.finalize();
		
		if (mVideoView != null){
			mVideoView.removeObserver(this);
			mVideoView.removeOnPlayIndexChangedListener(this);
			mVideoView.removeAllViews();
			mVideoView.finalize();
			mVideoView.destory();
			mVideoView = null;
		}
		
		if (mFocusLayout != null){
			mFocusLayout.removeAllViews();
			mFocusLayout = null;
		}
		
		if (mVideoLayout != null){
			mVideoLayout.removeAllViews();
			mVideoLayout = null;
		}
		
		if (mAssets != null){
			mAssets.clear();
			mAssets = null;
		}
		if(mContext != null){
			mContext = null;
		}
		mImageView = null;
		mTextView  = null;
		mPlayIcon  = null;
		
		mData = null;
	}
	/**
	 * 判断是否有视频在播放
	 * @return
	 */
	public boolean isPlaying(){
		if(mVideoView != null && (mVideoView.isPlaying() || mVideoView.isAdPlaying()) ){
			return true;
		}else{
			return false;
		}
	}
	
	private void setPlayImageVisible(int visible) {
		if(mVideoView != null){
			if (visible == VISIBLE) {
				mVideoView.setVisibility(GONE);
				if(mImageView != null){
					mImageView.setVisibility(visible);
				}
				if(mPlayIcon!= null){
					mPlayIcon.setVisibility(visible);
				}
			} else {
				if(mImageView != null){
					mImageView.setVisibility(GONE);
				}
				if(mPlayIcon!= null){
					mPlayIcon.setVisibility(GONE);
				}
				if(mVideoView.getParent() == null){  //说明播放器还没有添加到当前的layout
					mVideoView.setAnchorView(mVideoLayout ,(Activity)mContext);
				}
				mVideoView.setVisibility(VISIBLE);
			}
		}else{
			if(mImageView != null){
				mImageView.setVisibility(visible);
			}
			if(mPlayIcon!= null){
				mPlayIcon.setVisibility(visible);
			}
		}
		
	}

	@Override
	public void setData(BaseElement data) {
		if (data == null) {
			return;
		}
		this.mData = data;

		mTextView.setText(data.getName());

//		if (!mOffscreen) {
//			setPlayImageVisible(INVISIBLE);
//		} else {
//			setPlayImageVisible(VISIBLE);
//			ImageFetcherModule.getInstance().attachImage(data.getPicUrl(), mImageView, getResources().getDimensionPixelSize(R.dimen.d_5dp));
//			mPlayIcon.setImageResource(R.drawable.icon_play);
//		}
	}

	public void setData(List<AssetElement> assets) {
		if (assets == null){
			WLog.e(TAG, "传入的数据有误");
			return;
		}
		this.mAssets.clear();
		this.mAssets.addAll(assets);
		if (mPlayIndex>=0){
			setData(this.mAssets.get(mPlayIndex));
		}else {
			setData(this.mAssets.get(0));
		}
		if(playButDataIsNull && !mOffscreen){
			playVideo();
			WLog.e(TAG, "playButDataIsNull setData to playVideo()");
		}
		FrescoImageFetcherModule.getInstance().attachImage(this.mAssets.get(0).getPicUrl(), mImageView, getResources().getDimensionPixelSize(R.dimen.d_5dp));
		mPlayIcon.setImageResource(R.drawable.icon_play);
	}
	
	/**
	 * 视频小窗口得到焦点后自动播放视频
	 */
	private void playVideo() {

		if (mOffscreen || mVideoView.isPlaying() || mVideoView.isPreparing() || mVideoView.isAdPlaying()) {
			return;
		}
		if(isPlayedIndex){
			return;
		}
		setPlayImageVisible(INVISIBLE);

		if (this.mAssets!=null && this.mAssets.size() > 0) {
			playButDataIsNull = false;
			setData(this.mAssets.get(0));
			stopPlaying();
			mPlayIndex = 0;
			PlayerParams playerParams = new PlayerParams();
			playerParams.setAssetUrl((String) getTag());
			playerParams.setAssetList(mVideoView.getMediaController().getAssetList());
			playerParams.setPlayIndex(0);
			playerParams.setPlayType(WasuPlayerView.PLAY_TYPE_LOOP);
			mVideoView.play(playerParams);
		}else{
			WLog.e(TAG, "切换速度过快还没来得及setData就获得焦点调用playVideo导致mAssets数据为空");
			playButDataIsNull = true;
		}
	}
	/**
	 * 用户点击资产后播放对应的短视频资产
	 * @param index
	 */
	public void playVideo(int index) {
        if (mVideoView == null) {
            initVideoView(getContext());
        }
        isPlayedIndex = true;
		setPlayImageVisible(INVISIBLE);
		if (mPlayIndex == index && mVideoView.isPlaying()) {
			return;
		}
		if(this.mAssets == null){
			WLog.e(TAG, "点击资产播放短视频时mAssets为空");
			return;
		}
		if (index <= this.mAssets.size() - 1) {
			mPlayIndex = index;
		} else {
			mPlayIndex = 0;
		}
		if (mPlayIndex < this.mAssets.size()) {
			stopPlaying();
			setData(this.mAssets.get(mPlayIndex));
			/*用户主动切换资产，重置集数*/
			curPlayPosition = 1;
			PlayerParams playerParams = new PlayerParams();
			playerParams.setAssetUrl((String) getTag());
			playerParams.setPlayIndex(mPlayIndex);
			//playerParams.setAssetList(mVideoView.getMediaController().getAssetList());
			playerParams.setAssetList(new IAssetList() {

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

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

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

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

				@Override
				public String getPicUrl(int index) {
					return mAssets.get(index).getPicUrl();
				}

				@Override
				public void append(IAssetList assetList) {

				}

				@Override
				public String getPoint(int index) {
					return mAssets.get(index).getPoints();
				}
			});
			playerParams.setPlayType(WasuPlayerView.PLAY_TYPE_LOOP);
			mVideoView.play(playerParams);
		}
	}
	
	public void setOffScreen(boolean offScreen) {
		this.mOffscreen = offScreen;
		if (offScreen) {
			setPlayImageVisible(VISIBLE);
			if (mVideoView != null) {
				mVideoView.removeObserver(this);
				mVideoView.removeOnPlayIndexChangedListener(this);
				mVideoView.destory();
				if(mVideoView.getParent() != null){
					if(mVideoLayout != null){
						mVideoLayout.removeView(mVideoView);
					}
				}
				playButDataIsNull = false;
				mVideoView = null;
				isPlayedIndex = false;
			}else{
			}
		}
	}
	
	public void stopPlaying(){
		if(mVideoView != null){
			mVideoView.stopPlayback();
		}
	}

	@Override
	public void onClick(View view) {
		if(mVideoView != null){
			if (!mVideoView.isFullScreen()) {
				mVideoView.toggleFullScreen();
			}
		}
	}
	/**
	 * 视频切换为全屏播放
	 */
	public void toggleFullScreen(){
		if (!mVideoView.isFullScreen()) {
			mVideoView.toggleFullScreen();
		}
	}

	/**根据播放器的状态发送统计数据**/
	@Override
	public void onStart(MediaPlayer mediaPlayer) {
		if(mData != null){
			AssetElement elementData = (AssetElement) mData;  //获取当前正在播放资产数据
			PlayInfo playInfo = new PlayInfo(elementData.getId(), elementData.getTitle(), "", "", 
					elementData.getPlayUrl(), BuildType.SITE_ID, "","",elementData.getAssetType(),
					"-1","1","0",elementData.getCatName(),"begin","0",checkIsVip());
			//WasuStatistics.getInstance().playBegin(playInfo,AppUtil.playEnter);
			AppUtil.playInfo=playInfo;
		}
	}

	@Override
	public void onPreparing(MediaPlayer mediaPlayer) {
		//WasuStatistics.getInstance().prepareBegin();
	}

	@Override
	public void onPrepareComplete(MediaPlayer mediaPlayer) {
		//WasuStatistics.getInstance().prepareEnd();
	}

	@Override
	public void onSeeking(MediaPlayer mediaPlayer) {
		//WasuStatistics.getInstance().seekBegin();
	}

	@Override
	public void onSeekComplete(MediaPlayer mediaPlayer) {
		//WasuStatistics.getInstance().seekEnd();
	}

	@Override
	public void onProgress(int i, int i1, int i2) {
		
	}

	@Override
	public void onPause(MediaPlayer mediaPlayer) {
		//WasuStatistics.getInstance().onPause();
	}

	@Override
	public void onResume(MediaPlayer mediaPlayer) {
		//WasuStatistics.getInstance().onResume();
	}

	@Override
	public void onStop(MediaPlayer mediaPlayer) {
		/*if(mVideoView!=null){

			if(mediaPlayer != null){
				if(mVideoView.getCurrentPosition() > 0){
					playend(mVideoView.getCurrentPosition(), mVideoView.getDuration());
				}
			}else{  //在播放广告时mediaPlayer为null
				if(mVideoView.getCurrentPosition() > 0){
					playend(mVideoView.getCurrentPosition(), mVideoView.getDuration());
				}
			}

		}else{
//			playend(0,0);
		}*/
	}
	/**
	 * 在播放结束的时候统计视频的信息
	 * @param currentpositon 结束播放时候的播放位置
	 * @param duration       视频的总时长
	 */
	/*private void playend(int currentpositon,int duration) {
		AssetElement elementData = (AssetElement) mData;  //获取当前正在播放资产数据
		WasuStatistics.getInstance().setPlayinfo(new PlayInfo(elementData.getId(), elementData.getTitle(), "", "",
				elementData.getJsonUrl(), BuildType.SITE_ID,"",""+"",elementData.getAssetType(), curPlayPosition+"","1","0",elementData.getCatName(),"begin","0",checkIsVip()),AppUtil.playEnter);
		WasuStatistics.getInstance().playEnd(currentpositon, duration);

		// 调起播放结束的统计
		WLog.e("BigDataStatistics", "调起播放结束的统计channel");
		WasuStatistics.getInstance().use(this.mAssets.get(mPlayIndex).getId(), mVideoView.getCurrentPosition()+"");
	}*/
	private String checkIsVip() {
		String isvip= AuthSDK.getInstance().getValue("vipState");
		return isvip.isEmpty()?"0":isvip;
	}
	/**
	 * 播放结束的时候发送统计数据
	 */
	@Override
	public void onCompletion(MediaPlayer mediaPlayer) {
		/*if(mVideoView != null){
			playend(mVideoView.getCurrentPosition(),mVideoView.getDuration());
		}else{
//			playend(0, 0);
		}*/
		/*最后一个资产播放完毕*/
		if(mAssets != null && mPlayIndex == mAssets.size()-1 && curPlayPosition == totalCount){
            isPlayFinished = true;
			stopPlaying();
			setPlayImageVisible(VISIBLE);
			mTextView.setText(mAssets.get(0).getName());
			if(indexChangedListener != null){
				indexChangedListener.cleanPlayIndex(mPlayIndex);
			}
			mPlayIndex = -1;
		}
	}

	@Override
	public void onError(MediaPlayer mediaPlayer, int i, int i1) {

	}

	@Override
	public void onInfo(MediaPlayer mediaPlayer, int i, int i1) {
		/*if(i == MediaPlayer.MEDIA_INFO_BUFFERING_START){
			WasuStatistics.getInstance().bufferBegin();
		}else if(i == MediaPlayer.MEDIA_INFO_BUFFERING_END){
			WasuStatistics.getInstance().bufferEnd();
		}*/
	}

	@Override
	public void onStatusChanged(MediaPlayer mediaPlayer, int i) {
		
	}

	@Override
	public void onAdStatusChanged(int i, int i1) {

	}

	@Override
	public void onWasuError(int i, String s) {

	}

	@Override
	public void onWasuPlayLimit(int i, String s) {

	}
	
	@Override
	protected void onDetachedFromWindow() {
		// TODO Auto-generated method stub
		super.onDetachedFromWindow();
	}

	@Override
	public void onPlayIndexChanged(int index  ,int position, int total) {
		if (mAssets == null || mAssets.size() == 0) {
			return;
		}
		totalCount = total;
		if (index > mAssets.size() - 1) {
			index = mAssets.size() - 1;
		}

		if(indexChangedListener != null){
			indexChangedListener.onCurrentIndex(index);
		}

		if (index != mPlayIndex){ //切换资产
			mTextView.setText(mAssets.get(index).getName());
			/**连播后更新当前播放的资产数据mData,方便统计**/
			this.mData = null;
			this.mData = mAssets.get(index);
			curPlayPosition = 1;
		}else{  //没切换资产，只是切换了集数
			if(position >= 0){  //说明资产有集数
				curPlayPosition = position;
			}else{
				curPlayPosition = 1;
			}

		}

		mPlayIndex = index;
	}
		
}
