package basic.update.task;

import android.content.Context;
import android.os.AsyncTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import basic.update.ApkPathManager;

/**
 * 下载apk任务，并提醒用户升级
 * parameter:downloadUrl,saveName,updatenote
 */
public class RemindTask extends AsyncTask<String, Void, Boolean> {

	private Context context;

	/**
	 * 下载地址
	 */
	private String downloadUrl;

	/**
	 * task hook
	 * */
	IUpdateTaskListener iTaskListener = null;



	public RemindTask(Context c,IUpdateTaskListener taskListener) {
		this.context = c;
		this.iTaskListener = taskListener;
	}



	@Override
	protected Boolean doInBackground(String... params) {
		iTaskListener.onTaskStart();

		downloadUrl = params[0];

		File file = new File(ApkPathManager.getsInstance().getSavePath(), ApkPathManager.getsInstance().getSaveName());

		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(downloadUrl);
		HttpResponse response;
		try {
			response = client.execute(get);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				return false;
			}

			HttpEntity entity = response.getEntity();
			// 是否有已经下载完成的完整文件
			long contentLength = entity.getContentLength();
			File existFile = new File(ApkPathManager.getsInstance().getSavePath(), ApkPathManager.getsInstance().getSaveName() + ".apk");
			if (existFile.exists()) {
				if (contentLength == existFile.length()) {
					return true;
				} else {
					existFile.delete();
				}
			}

			InputStream is = entity.getContent();
			FileOutputStream fileOutputStream = null;
			if (is != null) {
				fileOutputStream = new FileOutputStream(file);
				byte[] buf = new byte[1024];
				int ch = -1;
				while ((ch = is.read(buf)) != -1) {
					fileOutputStream.write(buf, 0, ch);
				}
			}
			fileOutputStream.flush();
			if (fileOutputStream != null) {
				fileOutputStream.close();
			}
			if (is != null) {
				is.close();
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		if(result){
			//downlaod apk success
			iTaskListener.onTaskSuccess();
		}else{
			//download apk failed
			iTaskListener.onTaskFailed();
		}
	}

}
