package com.gensee.fastsdkdemo;

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

import com.gensee.download.ErrorCode;
import com.gensee.download.VodDownLoadEntity;
import com.gensee.download.VodDownLoadStatus;
import com.gensee.entity.InitParam;
import com.gensee.fastsdk.GenseeLive;
import com.gensee.fastsdk.core.GSFastConfig;
import com.gensee.fastsdk.entity.OfflinePlayParam;
import com.gensee.utils.GenseeLog;

import java.util.List;

//import android.support.v7.app.AppCompatActivity;

public class VodDownloadActivity extends Activity implements
		VodDownloadManager.DownloadUIListener {
	public static final String PARAM = "downparam";
	private String TAG = "VodDownloadActivity";
	private ListView mListView;
	private MyAdapter mMyAdapter;

	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;
	}

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

			@Override
			public void handleMessage(Message msg) {

				switch (msg.what) {
					case RESULT.DOWNLOAD_ERROR:
						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;

					default:
						break;
				}
			}

		};
	}

	private List<VodDownLoadEntity> getDownloadList(){

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

        return list;
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mListView = new ListView(this);
		setContentView(mListView);
		preferences = getPreferences(MODE_PRIVATE);

		ActionBar actionBar = getActionBar();
		if(actionBar != null){
			actionBar.setHomeButtonEnabled(true);
			actionBar.setDisplayHomeAsUpEnabled(true);
		}




		mMyAdapter = new MyAdapter(this);



		//初始化下载器
		VodDownloadManager.getIns().initDownLoader(this);
		//设置需要刷新的UI句柄,不设置界面不更新
		VodDownloadManager.getIns().setUICallback(this);

		mListView.setAdapter(mMyAdapter);
		notifyData();
		initHandler();

		//TODO 这里请注意，不要重复的add同一个点播,app自行记录处理重复下载问题
		VodDownloadManager.getIns().addDownload((InitParam) getIntent().getSerializableExtra(PARAM),this);
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				this.finish();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

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

	@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 onVodErr(final String msg) {
		if (!"".equals(msg)) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {

					Toast.makeText(VodDownloadActivity.this, msg, Toast.LENGTH_SHORT)
							.show();

				}
			});
		}
	}

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

	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.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.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(), "");
					//TODO 离线播放
					GenseeLive.startVod(VodDownloadActivity.this,new OfflinePlayParam(loacalPath,entity.getVodSubject()),new GSFastConfig());
				}
			});
			return convertView;
		}
	}

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

	}
}
