package com.example.mountaintravel.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.example.mountaintravel.adapter.Fragment5twoAdapter;
import com.example.mountaintravel.variable.Variable;
import com.smart.gtstrvl.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

public class UpdateManager {
	private SharedPreferences sp;
	private Context mContext;

	private String updateMsg = "有新的版本可以更新";
	
	public static String url = "";
	double version = 0.00;

	private Dialog noticeDialog;

	private Dialog downloadDialog;
	private static final String savePath = "/sdcard/gts/";
	private static final String saveFileName = savePath + "Updategts.apk";
	private ProgressBar mProgress;
	private static final int DOWN_UPDATE = 1;
	private static final int DOWN_OVER = 2;
	private int progress;
	private Thread downLoadThread;
	private String params = "";
	private String data = "";
	private String sign = "";
	private String partner = "androidAppUpdate";
	private String key = "androidAppUpdate";
	private boolean interceptFlag = false;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				installApk();
				break;
			}
		};
	};

	public UpdateManager(Context context) {
		this.mContext = context;
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
	}

	public void getdata() {
		Map<String, Object> paramsMap = new HashMap<String, Object>();

		data = StringChangeUtils.toJson(paramsMap);
		sign = StringChangeUtils.md5to32(data + key);
		Map<String, Object> paramsMap2 = new HashMap<String, Object>();
		paramsMap2.put("partner", partner);
		paramsMap2.put("key", key);
		paramsMap2.put("data", data);
		paramsMap2.put("sign", sign);
		params = StringChangeUtils.toJson(paramsMap2);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				loginByHttpClient();
			}
		}).start();
	}

	public void checkUpdateInfo() {

		// 获取当前软件包信息
		if (version != 0) {

			PackageInfo pi;
			try {
				pi = mContext.getPackageManager().getPackageInfo(
						mContext.getPackageName(),
						PackageManager.GET_CONFIGURATIONS);
				
				int versionCode = pi.versionCode;
				if (versionCode < version) {

					// 如果当前版本号小于服务端版本号,则弹出提示更新对话框
					showNoticeDialog();
				}

				if (versionCode == version && Variable.updata) {

					showNotice();
				}
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Message message = new Message();
				message.what = 10;
				handler.sendMessage(message);
			}
		}
		// 当前软件版本号

	}

	private void showNotice() {
		// TODO Auto-generated method stub
		Variable.updata = false;
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("已是最新版本");
		builder.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

			}
		});

		noticeDialog = builder.create();
		noticeDialog.show();
	}

	private void showNoticeDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("马上更新");
		builder.setMessage(updateMsg);
		builder.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				showDownloadDialog();
			}
		});
		builder.setNegativeButton("以后再说", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		noticeDialog = builder.create();
		noticeDialog.show();
	}

	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("正在下载更新...");
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);

		builder.setView(v);
		builder.setNegativeButton("取消更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.setCancelable(false);
		downloadDialog.show();
		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(UpdateManager.url);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);

					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						mHandler.sendEmptyMessage(DOWN_OVER);
						downloadDialog.dismiss();
						sp.edit().putBoolean("isloginsuccess", false).commit();
						sp.edit().putString("userName", "").commit();
						sp.edit().putString("userPass", "").commit();
						sp.edit().putString("sesskey", "").commit();
						sp.edit().putString("url", "").commit();
						sp.edit().putString("nick_name", "").commit();
						sp.edit().putBoolean("iferr11", false).commit();
						sp.edit().putBoolean("isFirstRun", true).commit();
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
				Message message = new Message();
				message.what = 10;
				handler.sendMessage(message);
			} catch (IOException e) {
				Message message = new Message();
				message.what = 10;
				handler.sendMessage(message);
				e.printStackTrace();
			}

		}
	};

	/**
	 * apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);

	}

	private void loginByHttpClient() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();

		HttpPost httpPost = new HttpPost("http://" + Variable.address
				+ "/terminal/androidAppUpdate");
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("out_msg", params));

			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);

			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {

				String is = EntityUtils.toString(response.getEntity(), "UTF-8");
				// String result = StreamTools.streamToString(is);
				byte[] outMsgBytes = is.getBytes("UTF-8");
				byte[] contentBytes = Base64.decodeBase64(outMsgBytes);
				String result = new String(contentBytes, "UTF-8");
				System.out.println(result);
				HashMap<String, Object> sss = StringChangeUtils.toObject(
						result, HashMap.class);
				HashMap<String, Object> aaa = StringChangeUtils.toObject(sss
						.get("result_data").toString(), HashMap.class);

				Object eventStartTime = aaa.get("url");
				Object description = aaa.get("description");
				Object eventEndTime = aaa.get("version");
				url = eventStartTime.toString();
				updateMsg = description.toString();
				String versionString = eventEndTime.toString();
				version = Double.parseDouble(versionString);
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			Message message = new Message();
			message.what = 10;
			handler.sendMessage(message);
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				checkUpdateInfo();

				break;
			case 10:
				ToastUtil.show(mContext, "数据获取异常");
				break;
			}
			super.handleMessage(msg);
		}
	};
}
