package com.wasu.cs.ui;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.ViewGroup;
import cn.com.wasu.main.AppUtil;
import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.IntentConstant;

import com.wasu.comp.videoview.IMediaControl;
import com.wasu.comp.videoview.IMediaListener;
import com.wasu.comp.videoview.UrlProperty;
import com.wasu.comp.videoview.WasuPlayerView;
import com.wasu.compfactory.WasuCompFactory;
import com.wasu.cs.model.SpecialColumnModel.AssetModel;
import com.wasu.cs.model.SpecialColumnModel.TagModel;
import com.wasu.cs.model.SpecialColumnModel.VideoModel;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.module.log.WLog;
import com.wasu.module.msgqueue.MsgIdConstant;
import com.wasu.module.msgqueue.MsgQueueModule;
import com.wasu.util.NetUtils;

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

import cn.com.wasu.main.AppUtil;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.IntentConstant;

public class ActivityLoopPlayer extends ActivityBase implements IMediaListener {
	public static final String ACTION = "com.wasu.action.loop.play";

	public static final String ASSET_PLAY_INFO = IntentConstant.PLAY_INFO.value();
	public static final String ASSET_PLAY_INDEX = IntentConstant.PLAY_INDEX.value();

	///////////////////////////////////////////////////////////////////////////////////////////

	private static final String TAG = "ActivityLoopPlayer";

	///////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * 组件工厂
	 */
	private WasuCompFactory wasuCompFactory = new WasuCompFactory();
	/**
	 * 播放器
	 */
	private WasuPlayerView player;
	/**
	 * 播控组件
	 */
	private MediaController mediaController;

	////////////////////////////////////////////////////////////////////////////////////////////

	private ArrayList<AssetModel> assetInfo;
	private int assetIndex;

	////////////////////////////////////////////////////////////////////////////////////////////

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

		player = wasuCompFactory.createWasuVideoView(this, BuildType.payTypeUrl);
		player.addObserver(this);

		addContentView(player, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

		configurePlayer();
	}
	
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {

		if (parseIntent()) {
			play();
		}

		super.onPostCreate(savedInstanceState);
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		
		setIntent(intent);
		
		player.stopPlayback();
		
		mediaController.clear();
		
		if (parseIntent()) {
			play();
		}
		
		super.onNewIntent(intent);
	}
	
	@Override
	public void finish() {
		
		if (mediaController != null) {
			mediaController.clear();
			mediaController.removeAllViews();
			mediaController = null;
		}
		
		if (player != null) {
			player = null;
		}
		
		super.finish();
	}

	@Override
	public void onStateChanged(int state) {
		if (AppUtil.ETHERNET_DISCONNECTED == state || AppUtil.WIFI_DISCONNECTED == state) {
			showErrorExitDlg("网络出错,请检查您的网络设置");
		} else {
			hideErrorExitDlg();
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			AssetModel assetModel = assetInfo.get(assetIndex);
			if (player != null && player.isPlaying()) {
				assetModel.setCurrentPosition(player.getCurrentPosition());
			} else {
				assetModel.setCurrentPosition(0);
			}
			MsgQueueModule.getInstance().postMsg(MsgIdConstant.MSGID_APP_MIN + 1, 0, null, assetModel);
		}
		return super.dispatchKeyEvent(event);
	}
	
	/**
	 * 配置播放器
	 */
	private void configurePlayer() {
		mediaController = new MediaController(this);
		mediaController.setPlayer(player);
		mediaController.setDisplayOption(
				//MediaController.DISPLAY_LEFTSIDEPANEL_CONTROLLER | 
				//MediaController.DISPLAY_BITRATE_CONTROLLER | 
				//MediaController.DISPLAY_PROMPT_AD_COUNTDOWN | 
				MediaController.DISPLAY_PROMPT_BUFFER | 
				//MediaController.DISPLAY_PROMPT_EXIT_AD | 
				//MediaController.DISPLAY_PROMPT_PAUSE_AD | 
				//MediaController.DISPLAY_SEEKBAR_CONTROLLER | 
				MediaController.DISPLAY_VOLUME_CONTROLLER | 
				MediaController.DISPLAY_VOLUME_MUTE_CONTROLLER);
		
		addContentView(mediaController, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

		player.addObserver(mediaController);
	}

	/**
	 * 解析传入数据
	 * 
	 * @return
	 */
	public boolean parseIntent() {

		assetInfo = getIntent().getParcelableArrayListExtra(ASSET_PLAY_INFO);
		assetIndex = getIntent().getIntExtra(ASSET_PLAY_INDEX, 0);

		if (assetInfo == null || assetInfo.get(assetIndex) == null) {
			showErrorExitDlg("传入数据为空");
			return false;
		}
		
		return true;
	}

	/**
	 * 开始播放
	 */
	public void play() {
		AssetModel assetModel = assetInfo.get(assetIndex);
		
		String url = getFitPlayUrl();
		if (url != null && TextUtils.isEmpty(url.trim())) {
			showErrorExitDlg("没有获取到播放串");
			return;
		}

		UrlProperty urlProperty = new UrlProperty();
		urlProperty.setPreferPlayer(IMediaControl.PreferPlayer.SYSTEM);
		urlProperty.setResourceId(String.valueOf(assetModel.getId()));
		urlProperty.setResourceName(assetModel.getTitle());
		urlProperty.setNodeId("");
		urlProperty.setPrice(0);
		urlProperty.setBitrate((int) getFitRate());
		urlProperty.setPpvPath("");
		urlProperty.setIsFree(true);
		
		try {
			player.setVideoPath(url, urlProperty);
		} catch (Exception e) {
			e.printStackTrace();
			assetIndex = (assetIndex + 1) % assetInfo.size();
			
			Intent intent = new Intent(ActivityLoopPlayer.ACTION);
			intent.putExtra(IntentConstant.PLAY_INFO.value(), assetInfo);
			intent.putExtra(IntentConstant.PLAY_INDEX.value(), assetIndex);
			startActivity(intent);
			return;
		}
		
		double pos = assetModel.getCurrentPosition();
		if (pos != 0) {
			player.seekTo((int) pos);
		}
		player.start();
		
	}
	
	/**
	 * 根据默认码率和集数获取加密播放串
	 * 
	 * @return
	 */
	public String getFitPlayUrl() {
		AssetModel assetModel = assetInfo.get(assetIndex);
		
		long fitRate = getFitRate();
		
		TagModel tagModel = null;
		List<TagModel> tagModels = assetModel.getTagList();
		for (int i = 0; i < tagModels.size(); i++) {
			tagModel = tagModels.get(i);
			if (tagModel.getRate() == fitRate) {
				break;
			}
		}
		
		if (tagModel == null) {
			return null;
		}
		
		VideoModel videoModel = tagModel.getVideoList().get(0);
		if (videoModel == null) {
			return null;
		}
		
		return videoModel.getPlayUrls().get(0);
		
	}

	/**
	 * 根据默认码率/用户选择的码率，选择当前最接近的码率
	 * 
	 * @return
	 */
	public long getFitRate() {
		AssetModel assetModel = assetInfo.get(assetIndex);
		
		long defaultRate = this.getSharedPreferences(MediaController.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getLong(MediaController.SHARED_PREFERENCES_KEY_CURRENT_RATE, Common.DEFAULT_PLAY_RATE);
		
		long fitRate = defaultRate;
		long absRate = Long.MAX_VALUE;
		List<TagModel> tagModels = assetModel.getTagList();
		for (int i = 0; i < tagModels.size(); i++) {
			if (tagModels.get(i) == null) {
				continue;
			}
			
			long tmpRate = tagModels.get(i).getRate();
			
			if (Math.abs(defaultRate - tmpRate) <= absRate) {
				fitRate = tmpRate;
				absRate = Math.abs(defaultRate - tmpRate);
			}
		}
		
		this.getSharedPreferences(MediaController.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).edit().putLong(MediaController.SHARED_PREFERENCES_KEY_CURRENT_RATE, fitRate).commit();
		return fitRate;
	}
	
	/**
	 * 退出播放
	 * 
	 * @param msg
	 */
	public void exit(String msg) {
		postMessage(msg);
		
		if (mediaController != null) {
			mediaController.clear();
			mediaController.removeAllViews();
			mediaController = null;
		}
		
		finish();
	}

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

	@Override
	public void onCompletion(MediaPlayer arg0) {
		assetInfo.get(assetIndex).setCurrentPosition(0);
		assetIndex = (assetIndex + 1) % assetInfo.size();
		
		Intent intent = new Intent(ActivityLoopPlayer.ACTION);
		intent.putExtra(IntentConstant.PLAY_INFO.value(), assetInfo);
		intent.putExtra(IntentConstant.PLAY_INDEX.value(), assetIndex);
		startActivity(intent);
	}

	@Override
	public void onError(MediaPlayer arg0, int arg1, int arg2) {
		showErrorExitDlg("播放器错误:" + arg1 + "," + arg2);
	}

	@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) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStop(MediaPlayer arg0) {
	}

	/**
	 * @param arg0
	 * 		WASU_ERROR_AUTH			 	= 设备授权注册失败
	 *		WASU_ERROR_QUERY_PRICE 		= 资产询价失败
	 *		WASU_ERROR_PAY				= 资产支付失败
	 *		WASU_ERROR_PLAYER			= 播放器异常
	 *		WASU_ERROR_UPM_TOKEN_EXPIRE	= token严重超期
	 * @param arg1
	 */
	@Override
	public void onWasuError(int arg0, String arg1) {
		if (NetUtils.isNetConnected(this)){
			assetIndex = (assetIndex + 1) % assetInfo.size();
			
			Intent intent = new Intent(ActivityLoopPlayer.ACTION);
			intent.putExtra(IntentConstant.PLAY_INFO.value(), assetInfo);
			intent.putExtra(IntentConstant.PLAY_INDEX.value(), assetIndex);
			startActivity(intent);
		}else{
			showErrorExitDlg("网络出错,请检查您的网络设置");
		}
	}

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

}
