package com.wasu.cs.module;

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

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 android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Toast;
import cn.com.wasu.main.R;

import com.wasu.cs.widget.WAlertDialog;
import com.wasu.module.IModule;
import com.wasu.module.log.WLog;
import com.wasu.util.MD5Utils;
import com.wasu.util.ShellUtils;
import com.wasu.util.ShellUtils.CommandResult;

/**
 * 下载安装第三方app
 * 
 * @author yuanjr@wasu.com
 */
public class InstallOtherAppModule extends IModule {

	public final static String TAG = InstallOtherAppModule.class.getSimpleName();

	private static InstallOtherAppModule mInstance;

	/**
	 * 升级文件保存路径，默认files目录
	 */
	private File mApkSavePath;

	private InstallOtherAppModule() {
	}

	public static InstallOtherAppModule getInstance() {
		if (mInstance == null) {
			synchronized (InstallOtherAppModule.class) {
				if (mInstance == null) {
					mInstance = new InstallOtherAppModule();
				}
			}
		}
		return mInstance;
	}

	/**
	 * 初始化
	 * 
	 * @param c
	 * @param updateInfo
	 */
	public void init(Context c) {
		if (isInited() || c == null) {
			return;
		}

		setContext(c);

		mApkSavePath = getContext().getFilesDir();

		setInited(true);
	}

	/**
	 * 执行下载操作
	 */
	public void dowanloadApk(String apkUrl) {
		if (!isInited()) {
			return;
		}
		String saveName = MD5Utils.encode(apkUrl);
		// 下载
		new RemindTask(getContext(), mApkSavePath).execute(apkUrl, saveName);

	}

	/**
	 * 下载apk任务，并提醒用户安装 parameter:downloadUrl,saveName,upinstallnote
	 */
	static class RemindTask extends AsyncTask<String, Void, Boolean> {

		/**
		 * 下载地址
		 */
		private String downloadUrl;
		/**
		 * 文件名称
		 */
		private String saveName;
		private Context context;
		/**
		 * 文件路径
		 */
		private File savePath;

		public RemindTask(Context c, File savePath) {
			this.context = c;
			this.savePath = savePath;
		}

		@Override
		protected Boolean doInBackground(String... params) {
			downloadUrl = params[0];
			saveName = params[1];

			File file = new File(savePath, saveName);

			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(downloadUrl);
			HttpResponse response;
			try {
				response = client.execute(get);
				if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
					Log.d("echo", "网络请求失败"+response.getStatusLine().getStatusCode());
					return false;
				}

				HttpEntity entity = response.getEntity();
				// 是否有已经下载完成的完整文件
				long contentLength = entity.getContentLength();
				File existFile = new File(savePath, saveName + ".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();
				Log.d("echo", "下载异常"+e.toString());
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// 下载失败
			if (!result) {
				WLog.e(InstallOtherAppModule.TAG, "[下载失败]");
				Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
				return;
			}
			Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
			File tmpFile = new File(savePath, saveName);
			// 加上.apk后缀名
			ShellUtils.execCommand("mv " + tmpFile.getAbsolutePath() + " " + tmpFile.getAbsolutePath() + ".apk", false, true);
			final File apkfile = new File(savePath, saveName + ".apk");
			if (!apkfile.exists()) {
				WLog.e(InstallOtherAppModule.TAG, "[更名失败]");
				return;
			}
			// 将文件权限改为666
			CommandResult shellRet = ShellUtils.execCommand("chmod 666 " + apkfile.getAbsolutePath(), false, true);
			if (shellRet.result == 0) {
				Uri uri = Uri.fromFile(apkfile);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(uri, "application/vnd.android.package-archive");
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			} else {
				WLog.e(InstallOtherAppModule.TAG, "[chmod升级文件失败]");
			}

		}
	}
}
