package com.gensee.voddemo;

import java.util.List;

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.util.Log;
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.demo.DemoConfig;
import com.gensee.demo.R;
import com.gensee.download.ErrorCode;
import com.gensee.download.VodDownLoadEntity;
import com.gensee.download.VodDownLoadStatus;
import com.gensee.download.VodDownLoader;
import com.gensee.download.VodDownLoader.OnDownloadListener;
import com.gensee.entity.InitParam;
import com.gensee.utils.GenseeLog;
import com.gensee.utils.StringUtil;

public class VodActivity extends Activity implements 
		OnDownloadListener, OnItemClickListener {

	private String TAG = "MainActivity";
	private ListView mListView;
	private MyAdapter mMyAdapter;
	private VodDownLoader mVodDownLoader;
	private View btnDownLoad, btnPlay;
	private SharedPreferences preferences;

	private static final int DURTIME = 2000;

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

	private Handler 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_FOR_PLAY:
				// 在线播放

				String vodId = (String) msg.obj;
				Intent i = new Intent(VodActivity.this,
						PlayActivity.class);
				i.putExtra("play_param", vodId);
				startActivity(i);
			
				break;
			case RESULT.ON_GET_VODOBJ_FOR_DOWNLOAD:
			
				// 下载
//				String vodId = (String) msg.obj;
				download((String) msg.obj);
				break;
			case RESULT.DOWNLOADER_INIT:
				if (mVodDownLoader != null) {
					List<VodDownLoadEntity> downloadList = mVodDownLoader.getDownloadList();
					for (VodDownLoadEntity vodDownLoadEntity : downloadList) {
						if (vodDownLoadEntity.isDownloading()) {
//							// 手动更改暂停状态
//							vodDownLoadEntity.setStatus(VodDownLoadStatus.STOP.getStatus());
							// 内部更新到数据库
							mVodDownLoader.download(vodDownLoadEntity.getDownLoadId());
						}
					}
					// 刷新UI
					mMyAdapter.notifyData(downloadList);
				}
				break;
			default:
				break;
			}
		}

	};

	private AbsVodInfoIniter playInfoIniter,downloadInfoIniter;
	
	private void download(String vodId) {
		mVodDownLoader.setAutoDownloadNext(true);
		int ret = mVodDownLoader.download(vodId);
		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.OBJECT_IS_NULL:
			Toast.makeText(this, "传入参数为空", DURTIME).show();
			break;
		case ErrorCode.OBJECT_NOT_EXIST:
			Toast.makeText(this, "目标不存在", 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);

		mMyAdapter = new MyAdapter(this);
		mListView = (ListView) findViewById(R.id.progressDoc);
		GenseeConfig.isNeedChatMsg = true;
		/*
		 * 代理使用，如果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;
//			}
//		});

		mVodDownLoader = VodDownLoader.instance(this, this, null);
		// 启动已存在且未完成的任务
		mVodDownLoader.download();
		// 刷新列表
		mHandler.sendEmptyMessage(RESULT.DOWNLOADER_INIT);

		mListView.setAdapter(mMyAdapter);
		createVodInfoIniters();
		initView();
	}

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

	public void createVodInfoIniters(){
		
		playInfoIniter = new AbsVodInfoIniter(this,mHandler) {
			
			@Override
			public void getVodObject(InitParam initParam) {
				//针对播放，取消之前的初始响应，保证响应的是最新一次的播放信息
				if(vodSite != null){
					vodSite.setVodListener(null);
				}
				super.getVodObject(initParam);
			}
			
			@Override
			public void onVodObject(String vodId) {
				//getVodObject响应  可以播放了
				mHandler.sendMessage(mHandler
						.obtainMessage(RESULT.ON_GET_VODOBJ_FOR_PLAY, vodId));
				vodSite.getQaHistory(vodId,1);

				vodSite.getChatHistory(vodId,1);
			}
		};
		downloadInfoIniter = new AbsVodInfoIniter(this,mHandler) {
			
			@Override
			public void onVodObject(String vodId) {
				//onVodObject 响应，可以用vodId下载了
				mHandler.sendMessage(mHandler
						.obtainMessage(RESULT.ON_GET_VODOBJ_FOR_DOWNLOAD, vodId));
			}
		};
		
	}
	
	public void initView() {
		btnDownLoad = findViewById(R.id.btnDownLoad);
		btnPlay = findViewById(R.id.btnDownPlay);
		
		btnPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				InitParam p = DemoConfig.getIns().getInitParam();
				p.setDownload(false);
				//播放前初始化
				playInfoIniter.getVodObject(DemoConfig.getIns().getInitParam());
			}
		});
		btnDownLoad.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				InitParam p = DemoConfig.getIns().getInitParam();
				//下载前初始化
				//注意，设置true  代表是下载
				p.setDownload(true);
				downloadInfoIniter.getVodObject(p);
			}
		});
	}


	@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(mVodDownLoader.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(mVodDownLoader.getDownloadList());
			}
		});
	}

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

			@Override
			public void run() {
				mMyAdapter.notifyData(mVodDownLoader.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) {
			this.entities = entities;
			notifyDataSetChanged();
		}

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

		@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.getnStatus();
			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.getnPercent() + "%");
			deleteButton.setOnClickListener(new OnClickListener() {

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

			stopButton.setOnClickListener(new OnClickListener() {

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

			playButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String loacalPath = preferences.getString(
							entity.getDownLoadId(), "");
					// 离线播放
					if (!StringUtil.isEmpty(loacalPath)) {
						Intent intent = new Intent(VodActivity.this,
								PlayActivity.class);
						intent.putExtra("play_path", loacalPath);
						startActivity(intent);

						downloadInfoIniter.getOfflineChatHistory(entity.getDownLoadId(),loacalPath,1);
						downloadInfoIniter.getOfflineQaHistory(entity,1);

					}
				}
			});
			return convertView;
		}
	}

	@Override
	public void onBackPressed() {
		// 退出下载相关的功能时，释放掉
		mVodDownLoader.release();
		mVodDownLoader = null;
		
		//释放initers
		if(playInfoIniter != null){
			playInfoIniter.shutdown();
		}
		if(downloadInfoIniter != null){
			downloadInfoIniter.shutdown();
		}
		super.onBackPressed();

	}

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

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

	

}
