package com.gensee.voddemo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gensee.common.GenseeConfig;
import com.gensee.config.ConfigApp;
import com.gensee.download.ErrorCode;
import com.gensee.download.VodDownLoadEntity;
import com.gensee.download.VodDownLoadStatus;
import com.gensee.download.VodDownLoader.OnDownloadListener;
import com.gensee.entity.InitParam;
import com.gensee.playerdemo.R;
import com.gensee.taskret.OnTaskRet;
import com.gensee.utils.GenseeLog;
import com.gensee.utils.StringUtil;
import com.gensee.vod.VodSite;

import java.util.List;

public class VodActivity extends Activity implements
		OnDownloadListener, OnItemClickListener {
	private String TAG = "VodActivity";
	private ListView mListView;
	private MyAdapter mMyAdapter;

	private View optionSelect;
	private View btnDownLoad, btnPlay;

	private AbsVodInfoIniter downloadIniter,playIniter;
	private SharedPreferences preferences;


	private static final int DURTIME = Toast.LENGTH_SHORT;

	public interface RESULT {
		int DOWNLOAD_ERROR = 2;
		int DOWNLOAD_STOP = 3;
		int DOWNLOADER_INIT = 4;
		int DOWNLOAD_START = 5;
		int ON_GET_VODOBJ = 100;
	}

	private Handler mHandler;
	private void initHandler(){
		mHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				switch (msg.what) {
					case RESULT.DOWNLOAD_ERROR:
						// notifyData();
						Toast.makeText(getApplicationContext(), "下载出错", DURTIME).show();
						break;
					case RESULT.DOWNLOAD_STOP:
						notifyData();
						Toast.makeText(getApplicationContext(), "下载停止", DURTIME).show();

						break;
					case RESULT.DOWNLOAD_START:
						notifyData();
						Toast.makeText(getApplicationContext(), "下载开始", DURTIME).show();
						break;
					case RESULT.ON_GET_VODOBJ:

						optionSelect.setVisibility(View.VISIBLE);
						final String vodId = (String) msg.obj;
						// download(vodId);
						// notifyData();
						// 在线播放
//						btnPlay.setOnClickListener(new OnClickListener() {
//
//							@Override
//							public void onClick(View v) {
//								optionSelect.setVisibility(View.GONE);
//								Intent i = new Intent(VodActivity.this,
//										PlayActivity.class);
//								i.putExtra("play_param", vodId);
//								startActivity(i);
//							}
//						});
//						// 下载
//						btnDownLoad.setOnClickListener(new OnClickListener() {
//
//							@Override
//							public void onClick(View v) {
//								optionSelect.setVisibility(View.GONE);
//								download(vodId);
//							}
//						});
						break;
					case RESULT.DOWNLOADER_INIT:
						notifyData();

						break;
					default:
						break;
				}
			}

		};
	}

	private List<VodDownLoadEntity> getDownloadList(){

		List<VodDownLoadEntity> list = VodDownloadManager.getIns().getDownloadList();

        return list;
    }
	private void download(String vodId) {
		//添加下载的时候设置自动下载下一个
		VodDownloadManager.getIns().setAutoDownloadNext(true);
		int ret = VodDownloadManager.getIns().download(vodId);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				downloadRet(ret);
			}
		});

	}
	private void downloadRet(int ret){
		switch (ret) {
			case ErrorCode.SUCCESS:
				Toast.makeText(this, "下载开始", DURTIME).show();
				// 调用成功，刷新列表
				notifyData();
				break;
			case ErrorCode.DOWNLOADING_HAVE_EXIST:
				Toast.makeText(this, "已有下载任务 。将被添加到队列稍后下载", DURTIME).show();
				break;
			case ErrorCode.DOWNLOADING_URL_NULL:
				Toast.makeText(this, "下载地址为空", DURTIME).show();
				break;
			case ErrorCode.OBJECT_HAVE_EXIST:
				Toast.makeText(this, "录制件已在下载队列中", DURTIME).show();
				break;
			case ErrorCode.ERR_UN_INVOKE_GETOBJECT:
				Toast.makeText(this, "请先调用vodSite.getObject(),onVodObject 响应后再下载", DURTIME).show();
				break;
			case ErrorCode.SDCARD_ERROR:
				Toast.makeText(this, "SD卡异常", DURTIME).show();
				break;
			default:
				break;
		}
	}



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vod_layout);
		preferences = getPreferences(MODE_PRIVATE);
		GenseeConfig.isNeedChatMsg = true;
		initHandler();
		startLogService();



		/*
		 * 代理使用，如果app有自己的网络代理，调用setTcpProxy， 然后在IGSOLProxy的ip和端口回调中返回相应的代理ip和代理端口，
		 * 没有代理则无需调用。此函数任何时候都可以调用。
		 */
		/*
		 * VodSite.setTcpProxy(new IProxy() {
		 * 
		 * @Override public int getProxyPort(int port) { // 返回代理端口 return port;
		 * }
		 * 
		 * @Override public String getProxyIP(String ip) { // 返回代理ip地址 return
		 * ip; } });
		 */
		
		/**
		 * 优先调用进行组件加载，有条件的情况下可以放到application启动时候的恰当时机调用
		 */
		VodSite.init(this, new OnTaskRet() {

			@Override
			public void onTaskRet(boolean arg0, int arg1, String arg2) {
				
			}
		});

		initData();
		initView();
		mHandler.sendEmptyMessage(RESULT.DOWNLOADER_INIT);
	}

	private void notifyData() {
		if (null != mMyAdapter) {
			mMyAdapter.notifyData(getDownloadList());
		}
	}

	public void initView() {
		//下载队列信息展现列表
		mListView = (ListView) findViewById(R.id.downloadlist);
		mMyAdapter = new MyAdapter(this);
		mListView.setAdapter(mMyAdapter);
		optionSelect = findViewById(R.id.optionSelect);
		//下载按钮
		btnDownLoad = optionSelect.findViewById(R.id.btnDownLoad);
		btnDownLoad.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//下载按钮事件响应，下载流程开始
				goDownload();
			}
		});
		//播放按钮
		btnPlay = optionSelect.findViewById(R.id.btnDownPlay);
		btnPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//播放按钮事件，播放流程开始
				goPlay();
			}
		});


	}


	private void initData(){
		//初始化下载器
		VodDownloadManager.getIns().initDownLoader(this);
		//设置需要刷新的UI句柄,不设置界面不会更新
		VodDownloadManager.getIns().setUICallback(this);
		//点播下载信息处理器的初始化
		downloadIniter = new AbsVodInfoIniter(getApplicationContext(),mHandler) {
			@Override
			public void onVodObject(String vodId) {
				//响应后进入vodDownloader下载

				download(vodId);
			}
		};
		//点播播放信息处理器的初始化
		playIniter = new AbsVodInfoIniter(getApplicationContext(),mHandler) {
			@Override
			public void onVodObject(String vodId) {
				//把vodId传递给PlayActivity 进行播放，注意每一次播放都需要先getVodObject
				Intent i = new Intent(VodActivity.this,
						PlayActivity.class);
				i.putExtra("play_param", vodId);
				startActivity(i);

			}

			@Override
			public void getVodObject(InitParam initParam) {
				if (vodSite != null) {
					vodSite.setVodListener(null);
				}
				initParam.setDownload(false);
				super.getVodObject(initParam);
			}
		};
	}
	/**************************下载过程的相关回调OnDownloadListener******************/
	@Override
	public void onDLFinish(String downLoadId, String localPath) {
		GenseeLog.i(TAG, "onDLFinish downLoadId = " + downLoadId);
		preferences.edit().putString(downLoadId, localPath).commit();
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				mMyAdapter.notifyData(getDownloadList());
			}
		});
	}

	@Override
	public void onDLPosition(String downLoadId, final int percent) {
		GenseeLog.i(TAG, "onDLPosition downLoadId = " + downLoadId
				+ " percent = " + percent);
		// 下载过程中
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mMyAdapter.notifyData(getDownloadList());
			}
		});
	}

	public void onDLPrepare(String downLoadId) {
		GenseeLog.i(TAG, "onDLPrepare downLoadId = " + downLoadId);
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mMyAdapter.notifyData(getDownloadList());
			}
		});
	}

	@Override
	public void onDLStart(String downLoadId) {
		GenseeLog.i(TAG, "onDLStart downLoadId = " + downLoadId);
		// 下载开始
		mHandler.sendEmptyMessage(RESULT.DOWNLOAD_START);
	}

	@Override
	public void onDLStop(String downLoadId) {
		// 下载停止
		GenseeLog.i(TAG, "onDLStop downLoadId = " + downLoadId);
		mHandler.sendEmptyMessage(RESULT.DOWNLOAD_STOP);

	}

	@Override
	public void onDLError(String downLoadId, int errorCode) {
		GenseeLog.i(TAG, "onDLError downLoadId = " + downLoadId
				+ " errorCode = " + errorCode);
		mHandler.sendEmptyMessage(RESULT.DOWNLOAD_ERROR);
	}

    @Override
    public void onRecordInfo(String s, long l, long l1, long l2) {

    }

    class MyAdapter extends BaseAdapter {
		private List<VodDownLoadEntity> entities = null;
		private Context mContext;

		public MyAdapter(Context mContext) {
			this.mContext = mContext;
		}

		public void notifyData(List<VodDownLoadEntity> entities) {
			if(entities != null){
                this.entities = entities;
                notifyDataSetChanged();
			}
		}

		@Override
		public int getCount() {
			int count = entities == null ? 0 : entities.size();
			return count;
		}

		@Override
		public Object getItem(int position) {
			return entities.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			if (null == convertView) {
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.listitem, null);
			}
			final VodDownLoadEntity entity = (VodDownLoadEntity) getItem(position);
			TextView mTextView = (TextView) convertView
					.findViewById(R.id.downloadcontextid);
			TextView mProTextView = (TextView) convertView
					.findViewById(R.id.downloadprogressitem);
			ImageButton deleteButton = (ImageButton) convertView
					.findViewById(R.id.deleteDownload);
			ImageButton stopButton = (ImageButton) convertView
					.findViewById(R.id.stopdownload);
			final int status = entity.getStatus();
			if (status == VodDownLoadStatus.FINISH.getStatus()) {
				stopButton.setVisibility(View.INVISIBLE);
			} else {
				stopButton.setVisibility(View.VISIBLE);
				if (status == VodDownLoadStatus.STOP.getStatus()) {
					stopButton.setImageResource(R.drawable.down_loading);
				} else if (status == VodDownLoadStatus.BEGIN.getStatus()
						|| status == VodDownLoadStatus.START.getStatus()) {
					stopButton.setImageResource(R.drawable.down_normal);
				} else {
					stopButton.setImageResource(R.drawable.down_loading);
				}
			}
			ImageButton playButton = (ImageButton) convertView
					.findViewById(R.id.palydownload);
			mTextView.setText(entity.getVodSubject() + " ");
			mProTextView.setText(entity.getPercent() + "%");
			deleteButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					VodDownloadManager.getIns().delete(entity.getDownLoadId());
					// 同时删除已经存放的本地路径
					preferences.edit().remove(entity.getDownLoadId());
					// 删除之后刷新
					notifyData(getDownloadList());
				}
			});

			stopButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (status == VodDownLoadStatus.FAILED.getStatus()
							|| status == VodDownLoadStatus.STOP.getStatus()
							|| status == VodDownLoadStatus.DENY.getStatus()) {
						VodDownloadManager.getIns().download(entity.getDownLoadId());
					} else if (status == VodDownLoadStatus.BEGIN.getStatus()
							|| status == VodDownLoadStatus.START.getStatus()) {
						VodDownloadManager.getIns().stop(entity.getDownLoadId());
					}
				}
			});

			playButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String loacalPath = preferences.getString(
							entity.getDownLoadId(), "");
					// 离线播放，把下载完成后响应的本地地址传递给PlayActivity
					if (!StringUtil.isEmpty(loacalPath)) {
						Intent intent = new Intent(VodActivity.this,
								PlayActivity.class);
						intent.putExtra("play_path", loacalPath);
						startActivity(intent);
					}
				}
			});
			return convertView;
		}
	}

	@Override
	public void onBackPressed() {
		stopLogService();
		super.onBackPressed();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
	}


	/**
	 * 用InitPram初始化后下载
	 *
	 */
	private void goDownload(){
		//TODO 如果是列表点击下载那new 一个InitParam 对象，且设置为下载（p.setDownload(true) )
		InitParam p = ConfigApp.getIns().getInitParam();
		p.setDownload(true);
		downloadIniter.getVodObject(p);
	}

	private void goPlay(){
		InitParam p = ConfigApp.getIns().getInitParam();
		playIniter.getVodObject(p);

	}

	
	private void startLogService() {
//		startService(new Intent(this, LogCatService.class));
	}

	private void stopLogService() {
//			stopService(new Intent(this, LogCatService.class));
	}
}
