package com.wasu.cs.widget;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
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;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.IAssetList;
import com.wasu.cs.ui.FragmentNeteaseNewsBody;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
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 chenming on 2016/8/2.
 *
 * @author chenming
 * @Description: 网易新闻专区的视频播放控件
 * @email chenming@wasu.com
 * @date 2016/8/2 18:30
 */

public class NeteaseNewsVideoLayout extends RelativeLayout implements
		StatisticsOberserverInterface, View.OnClickListener,
		WasuPlayerView.OnPlayIndexChangedListener {
	private final static String TAG = "NeteaseNewsVideoLayout";

	//UI
	private Context mContext;
	private WasuPlayerView mVideoView;//播放器
	private TextView mtitletext;    //新闻标题  
	//private ImageView mplayicon;    //播放按钮
	private FocusLinearLayout mFocusLayout;
	private RelativeLayout mVideoLayout;
	private PlayIndexChangedListener indexChangedListener;
	private WasuPlayerView.OnScreenChangedListener mOnScreenChangedListener;//全屏切换监听
	private FragmentNeteaseNewsBody parent;
	//数据
	private CatData.AssetElement mData;
	private List<CatData.AssetElement> mAssets = new ArrayList<>();
	private PlayerParams mPlayerParams = new PlayerParams();
	private SparseArray<CatData> mCatDate = new SparseArray<>();
	private SparseArray<String> jsonUrls = new SparseArray<>();
	//状态标记
	private int mPlayIndex = -1;                //当前播放的是第几个资产
	private int mTabIndex = -1;                //当前播放的是第几个tab
	private boolean isRecPlayed = false;

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

	public NeteaseNewsVideoLayout(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context);

	}

	public NeteaseNewsVideoLayout(Context context) {
		super(context);
		init(context);

	}

	public void setParent(FragmentNeteaseNewsBody parent) {
		this.parent = parent;
	}

	private void init(final Context context) {
		mContext = context;
		LayoutInflater.from(context).inflate(R.layout.neteasenews_video_layout, this);
		//初始化focuslayout
		mFocusLayout = (FocusLinearLayout) findViewById(R.id.neteasevideofocusLayout);
		//初始化videolayout
		mVideoLayout = (RelativeLayout) findViewById(R.id.netease_videoLayout);
		mVideoLayout.setFocusable(true);
		mVideoLayout.setClickable(true);
		mVideoLayout.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					mFocusLayout.requestFocus();
				}
			}
		});

		//初始化video缩略图、播放icon、新闻标题
		mtitletext = (TextView) findViewById(R.id.netease_news_title);
		//mplayicon = (ImageView) findViewById(R.id.netease_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);
		}
		mVideoView.addOnScreenChangedListener(mOnScreenChangedListener);
	}

	/**
	 * 为视频播放器设置播放index监听器
	 *
	 * @param PlayIndexChangedListener
	 */
	public void setOnPlayIndexChangedListener(PlayIndexChangedListener PlayIndexChangedListener) {
		this.indexChangedListener = PlayIndexChangedListener;
	}

	public void setOnScreenChangedListener(WasuPlayerView.OnScreenChangedListener onScreenChangedListener) {
		mOnScreenChangedListener = onScreenChangedListener;
	}

	public void setJsonUrls(SparseArray<String> jsonUrls) {
		this.jsonUrls = jsonUrls;
	}

	public void setCatDate(SparseArray<CatData> catDate) {
		mCatDate = catDate;
	}

	public void addCatData(CatData catData, int pos) {
		mCatDate.put(pos, catData);
	}

	/**
	 * 监听播放器当前播放index接口
	 */
	public interface PlayIndexChangedListener {
		public void onCurrentIndex(int index);

		/*当所有的资产播放完成清除“播放中”指示器*/
		public void cleanPlayIndex(int index);
	}

	public void removePlayIndexChangedListener() {
		if (indexChangedListener == null) {
			return;
		} else {
			indexChangedListener = null;
		}
	}

	@Override
	protected 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;
		}
		mtitletext = null;
		//mplayicon = null;

		mData = null;
	}

	/**
	 * 判断是否有视频在播放
	 */
	public boolean isPlaying() {
		if (mVideoView != null && (mVideoView.isPlaying() || mVideoView.isAdPlaying())) {
			return true;
		} else {
			return false;
		}
	}

	public void setData(CatData.AssetElement data) {
		this.mData = data;
		mtitletext.setText(mData.getTitle());
		/*if (mplayicon.getVisibility() == INVISIBLE) {
			mplayicon.setVisibility(VISIBLE);
		}
		mplayicon.setImageResource(R.drawable.play_icon);*/
	}

	public void setData(List<CatData.AssetElement> assets) {
		if (assets == null) {
			return;
		} else if (assets != mAssets) {
			this.mAssets.clear();
			this.mAssets.addAll(assets);
		}

	}

	public void playRecVideo(String assetjsonurl,DemandProgram demandProgram) {
		isRecPlayed = true;
		if (mVideoView == null) {
			initVideoView(getContext());
		}
		if (mtitletext != null) {
			mtitletext.setText(demandProgram.getTitle());
		}
		PlayerParams playerParams = new PlayerParams();
		playerParams.setAssetUrl(assetjsonurl);
		playerParams.setDomain(BuildType.HTTP_DOMAIN);
		playerParams.setAssetInfo(demandProgram);
		mVideoView.play(playerParams);

	}

	/**
	 * 用户点击资产后播放对应的短视频资产
	 *
	 * @param tabIndex  tab索引
	 * @param listIndex 列表索引
	 */
	public void playVideo(int tabIndex, int listIndex) {
		if (mVideoView == null) {
			initVideoView(getContext());
		}
		if (mCatDate.get(tabIndex) != null) {
			setData(mCatDate.get(tabIndex).getAssets());
			setData(mAssets.get(listIndex));
		}
		if (mPlayIndex == listIndex && mTabIndex == tabIndex && mVideoView.isPlaying()) {
			mVideoView.toggleFullScreen();
			return;
		}

		if (listIndex < this.mAssets.size()) {
			if (mTabIndex == tabIndex) {//不切换tab时只切换index进行播放
				stopPlaying();
				mPlayerParams.setPlayIndex(listIndex);
				mVideoView.ignoreAllAd();//跳过所有广告
				mVideoView.play(mPlayerParams);
				mPlayIndex = listIndex;
			} else {
				stopPlaying();
				PlayerParams playerParams = new PlayerParams();
				playerParams.setAssetUrl(jsonUrls.get(tabIndex));
				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.setPlayIndex(listIndex);
				playerParams.setPlayType(WasuPlayerView.PLAY_TYPE_LOOP);
				mVideoView.ignoreAllAd();//跳过所有广告
				mVideoView.play(playerParams);
				mPlayerParams = playerParams;
				mTabIndex = tabIndex;//更新tab索引
				mPlayIndex = listIndex;//更新list索引
			}

		}


	}


	public void stopPlaying() {
		if (mVideoView != null) {
			mVideoView.stopPlayback();
			if (mVideoView.getVideoView() != null) {
				mVideoView.getVideoView().skipCurrentAd();
			}
		}
	}


	@Override
	public void onClick(View v) {
		toggleFullScreen();
	}

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

	private String checkIsVip() {
		String isvip = AuthSDK.getInstance().getValue("vipState");
		return isvip.isEmpty() ? "0" : isvip;
	}

	@Override
	public void onStart(MediaPlayer mediaPlayer) {
		if (mData != null) {
			CatData.AssetElement elementData =  mData;  //获取当前正在播放资产数据
			PlayInfo playInfo = new PlayInfo(
					elementData.getId(),
					elementData.getTitle(),
					mVideoView.getRealUrl(),
					"",
					elementData.getAssetType(),
					BuildType.SITE_ID,
					"",
					"" + "",
					elementData.getAssetType(),
					mPlayIndex + "",
					"1",
					"0",
					elementData.getCatName(),
					"begin",
					"0",
					checkIsVip());
			AppUtil.playInfo = playInfo;
		}
	}

	@Override
	public void onPreparing(MediaPlayer mediaPlayer) {
	}

	@Override
	public void onPrepareComplete(MediaPlayer mediaPlayer) {
	}

	@Override
	public void onSeeking(MediaPlayer mediaPlayer) {
	}

	@Override
	public void onSeekComplete(MediaPlayer mediaPlayer) {
	}

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

	@Override
	public void onPause(MediaPlayer mediaPlayer) {
	}

	@Override
	public void onResume(MediaPlayer mediaPlayer) {
	}

	@Override
	public void onStop(MediaPlayer mediaPlayer) {
	}


	@Override
	public void onCompletion(MediaPlayer mediaPlayer) {
		if (isRecPlayed) {
			playVideo(0, 0);//after rec video played,then play tab(0,0)
			isRecPlayed = false;
		}
		if (mPlayIndex == mAssets.size() - 1) {
			playVideo(mTabIndex, 0);
		}
	}

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

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

	}

	@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
	public void onPlayIndexChanged(int index, int position, int total) {
		if (mAssets == null || mAssets.size() == 0) {
			return;
		}
		//自动连播
		/*if (index == mAssets.size()) {
			mPlayIndex = 0;
			//mTabIndex++;
			if (mTabIndex <= mCatDate.size() - 1) {
				playVideo(mTabIndex, mPlayIndex);//循环播放列表第一条资产
				parent.savePlayingState(mTabIndex, mPlayIndex);
				indexChangedListener.onCurrentIndex(mPlayIndex);
				return;
			}
		} else {
			if (indexChangedListener != null) {
				indexChangedListener.onCurrentIndex(index);
			}
		}*/
		if (indexChangedListener != null) {
			indexChangedListener.onCurrentIndex(index);
		}
		if (index != mPlayIndex && index < mAssets.size()) { //切换资产
			mtitletext.setText(mAssets.get(index).getName());
			this.mData = null;
			this.mData = mAssets.get(index);

		}
		mPlayIndex = index;
	}

}
