package com.usai.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import java.util.UUID;

import java.util.logging.Handler;


import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import com.usai.redant.raimage.RedAntApplication;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import static android.R.attr.key;
import static android.R.attr.parentActivityName;
import static android.R.attr.tag;

public class Network
{
	private static final int	REQUEST_TIMEOUT					= 15 * 1000;			// request
																						// time
																						// out
																						// 20
																						// secs
	private static final int	SO_TIMEOUT						= 15 * 1000;			// so
																						// time
																						// out
																						// 20
																						// secs;
	public static int			AP_USER_AUTH					= 1;
	public static int			AP_USER_NOT_AUTH				= 2;
	public static int			AP_USER_NOT_EXIST				= 3;
	public static int			AP_UPLOAD_SUCCESS				= 4;
	public static int			AP_UPLOAD_FAIL					= 5;
	//
	// public static final int RESULT_FALSE = 0;
	// public static final int RESULT_TRUE = 1;
	// public static final int RESULT_NET_ERROR = 3;
	// public static final int RESULT_ERROR = 5;
	// public static final int RESULT_LOCALFILE_ERROR= 7;
	// public static final int RESULT_USERAUTH_ERROR = 9;

	public static int			AP_MESSAGE_NEW					= 5;
	public static int			AP_MESSAGE_NONE					= 6;
	//
	public static final int		RESULT_FALSE					= 0;
	public static final int		RESULT_TRUE						= 2;
	public static final int		RESULT_NET_ERROR				= -3;
	public static final int		RESULT_NET_NOTAVAILABLE			= -4;
	public static final int		RESULT_ERROR					= -5;
	public static final int		RESULT_LOCALFILE_ERROR			= -7;
	public static final int		RESULT_USERAUTH_ERROR			= -9;
	public static final int		RESULT_UPDATE_USERAUTH_ERROR	= -11;
	public static final int		RESULT_SESSION_EXPIRED			= -13;
	public static final int		RESULT_VER_LOW					= -15;
	public static final int		STATUS_WAIT						= -17;
	static String				URL_UPLOAD_PHOTO				= "handset.php";
	@Deprecated
	static String				URL_VERIFY_USER					= "handset_login.php";
	static String				URL_LOGIN					= "index.php?_action=handset_new ";

	public static class SSLSocketFactoryEx extends SSLSocketFactory
	{

		SSLContext	sslContext	= SSLContext.getInstance("TLS");

		public SSLSocketFactoryEx(KeyStore truststore)
				throws NoSuchAlgorithmException, KeyManagementException,
				KeyStoreException, UnrecoverableKeyException
		{
			super(truststore);

			TrustManager tm = new X509TrustManager()
			{
				public java.security.cert.X509Certificate[] getAcceptedIssuers()
				{
					return null;
				}

				@Override
				public void checkClientTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException
				{
				}

				@Override
				public void checkServerTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException
				{
				}
			};
			sslContext.init(null, new TrustManager[] { tm }, null);
		}

		@Override
		public Socket createSocket(Socket socket, String host, int port,
				boolean autoClose) throws IOException {
			return sslContext.getSocketFactory().createSocket(socket, host,
					port, autoClose);
		}

		@Override
		public Socket createSocket() throws IOException
		{
			return sslContext.getSocketFactory().createSocket();
		}
	}

/*	private static HttpURLConnection getNewHttpConnection()
{



}*/
	private static HttpClient getNewHttpClient()
	{
		try
		{
			KeyStore trustStore = KeyStore.getInstance(KeyStore
					.getDefaultType());
			trustStore.load(null, null);

			SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			registry.register(new Scheme("https", sf, 443));

			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
					params, registry);

			return new DefaultHttpClient(ccm, params);
		}
		catch (Exception e)
		{
			dbgUtil.fileLog(e.toString());
			return new DefaultHttpClient();
		}
	}
	private static String createPostParameters(Bundle parms) throws UnsupportedEncodingException {
		StringBuilder result = new StringBuilder();
		boolean first = true;
		for(String key : parms.keySet()){
			if (first)
				first = false;
			else
				result.append("&");

			result.append(URLEncoder.encode(key, "UTF-8"));
			result.append("=");
			result.append(URLEncoder.encode(parms.get(key).toString(), "UTF-8"));
		}

		return result.toString();
	}
	public static String getJson(String url, Bundle parms)
	{
		String TAG = "net_dbg@GetJson";
		Log.d(TAG, "entry");
		String ret=null;

		HttpURLConnection connection = null;

		try {


			URL _url;
			_url = new URL(url);
			connection = (HttpURLConnection) _url.openConnection();
			// 设置请求方式
			connection.setRequestMethod("POST");
			// 设置编码格式
			connection.setRequestProperty("Charset", "UTF-8");
			// 传递自定义参数
//			connection.setRequestProperty("MyProperty", "this is me!");

			if(!TextUtils.isEmpty(RedAntApplication.user))
				parms.putString("user", AES.encrypt("usai", RedAntApplication.user));
			if(!TextUtils.isEmpty(RedAntApplication.password))
				parms.putString("password", AES.encrypt("usai", RedAntApplication.password));

			parms.putString("app_ver", RedAntApplication.getInstance()
					.getPackageManager()
					.getPackageInfo("com.usai.redant.raimage", 0).versionName);
			parms.putInt("app_short_ver", RedAntApplication.getInstance()
					.getPackageManager()
					.getPackageInfo("com.usai.redant.raimage", 0).versionCode);

			parms.putString("deviceid",RedAntApplication.device_id);




			Set<String> keys = parms.keySet();
			Log.d(TAG, "================parms============");
			for (String key : keys)
			{
				if (key.contains("_file"))
				{
				}
				else
				{
//					connection.setRequestProperty(key, parms.get(key).toString());
					Log.d(TAG, "key=" + key + "    val="
							+ parms.get(key).toString());
				}
//					reqEntity.addPart(key, new StringBody());

			}
			Log.d(TAG, "================parms============");

			Log.d(TAG,"URL: "+url);
			// 设置容许输出
			connection.setDoInput(true);
			connection.setDoOutput(true);


			OutputStream os = connection.getOutputStream();
			BufferedWriter writer = new BufferedWriter(
					new OutputStreamWriter(os, "UTF-8"));
			writer.write(createPostParameters(parms));

			writer.flush();
			writer.close();
			os.close();

		/*// 上传一张图片
		FileInputStream file = new FileInputStream(Environment.getExternalStorageDirectory().getPath()
				+ "/Pictures/Screenshots/Screenshot_2015-12-19-08-40-18.png");
		OutputStream os = connection.getOutputStream();
		int count = 0;
		while((count=file.read()) != -1){
			os.write(count);
		}
		os.flush();
		os.close();
*/
			// 获取返回数据
			if(connection.getResponseCode() == 200){
				InputStream is = connection.getInputStream();

				BufferedReader br = new BufferedReader(
						new InputStreamReader(is, "utf-8"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = br.readLine()) != null)
				{
					sb.append(line + "\n");
				}

				Log.d(TAG, "Response: content begin");
				Log.d(TAG, sb.toString());
				Log.d(TAG, "Response: content end");

				if (sb.length() <= 0)
				{

					ret= null;
				}
				ret= sb.toString();

//				Message msg = Message.obtain();
//				msg.what = 0;
//				postHandler.sendMessage(msg);
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			dbgUtil.fileLog(e.toString());
			Log.e(TAG, e.toString());

		} catch (ProtocolException e) {
			e.printStackTrace();
			dbgUtil.fileLog(e.toString());
			Log.e(TAG, e.toString());

		} catch (MalformedURLException e) {
			e.printStackTrace();
			dbgUtil.fileLog(e.toString());
			Log.e(TAG, e.toString());

		} catch (IOException e) {
			e.printStackTrace();
			dbgUtil.fileLog(e.toString());
			Log.e(TAG, e.toString());

		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		} finally {

			if(connection!=null){
				connection.disconnect();
			}
		}
		return ret;

	}
	@Deprecated
	public static String getJson_d(String url, Bundle parms)
	{
		String TAG = "net_dbg@GetJson";
		Log.d(TAG, "entry");

		// parms.putString("sessionid",
		// ApexTrackingApplication.get_sessionid());

		// if (true)
		// return fakegetJson(url);
		try
		{
			// BasicHttpParams httpParams = new BasicHttpParams();
			// HttpConnectionParams.setConnectionTimeout(httpParams,
			// REQUEST_TIMEOUT);
			// HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
			HttpClient client = getNewHttpClient();// new
													// DefaultHttpClient(httpParams);
			HttpPost post = new HttpPost(url);
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			Set<String> keys = parms.keySet();
			Log.d(TAG, "================parms============");
			for (String key : keys)
			{
				if (key.contains("_file"))
				{
				}
				else
					reqEntity.addPart(key, new StringBody(parms.get(key)
							.toString()));
				Log.d(TAG, "key=" + key + "    val="
						+ parms.get(key).toString());
			}
			Log.d(TAG, "================parms============");

			post.setEntity(reqEntity);
			HttpResponse response = client.execute(post);
			int statucode = response.getStatusLine().getStatusCode();
			if (statucode == HttpStatus.SC_OK)
			{
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null)
				{
					Log.d(TAG,
							"Response: content len==>"
									+ resEntity.getContentLength());
					InputStream is = resEntity.getContent();
					try
					{

						BufferedReader br = new BufferedReader(
								new InputStreamReader(is, "utf-8"), 8);
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = br.readLine()) != null)
						{
							sb.append(line + "\n");
						}

						Log.d(TAG, "Response: content begin");
						Log.d(TAG, sb.toString());
						Log.d(TAG, "Response: content end");

						if (sb.length() <= 0)
						{

							return null;
						}
						return sb.toString();

					}
					catch (Exception e)
					{
						dbgUtil.fileLog(e.toString());
						Log.e(TAG, e.toString());
						return null;
						// TODO: handle exception
					}
					finally
					{
						is.close();

					}

				}
				else
				{
					/*
					 * resEntity is null
					 */
					Log.d(TAG, "RESPONSE ENTITY IS NULL");
					return null;
				}

			}
			else
			{
				/*
				 * Http error; out put error code;
				 */
				Log.d(TAG, "HTTP " + statucode);

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null)
				{

					InputStream is = resEntity.getContent();
					try
					{

						BufferedReader br = new BufferedReader(
								new InputStreamReader(is, "utf-8"), 8);
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = br.readLine()) != null)
						{
							sb.append(line + "\n");
						}

						Log.d(TAG, "Response: content begin");
						Log.d(TAG, sb.toString());
						Log.d(TAG, "Response: content end");
						return null;
					}
					catch (Exception e)
					{
						dbgUtil.fileLog(e.toString());
						Log.e(TAG, e.toString());
						return null;
						// TODO: handle exception
					}
					finally
					{
						is.close();

					}

				}
				else
				{
					/*
					 * resEntity is null
					 */
					Log.e(TAG, "RESPONSE ENTITY IS NULL");
					return null;
				}
			}

		}
		catch (ConnectTimeoutException e)
		{
			Log.d(TAG, "request time out");
			dbgUtil.fileLog(e.toString());
			return null;

		}
		catch (SocketTimeoutException e)
		{
			Log.d(TAG, "socket time out");
			dbgUtil.fileLog(e.toString());
			return null;
		}
		catch (UnknownHostException e)
		{
			Log.d(TAG, e.toString());
			dbgUtil.fileLog(e.toString());
			return null;
		}
		catch (HttpHostConnectException e)
		{
			Log.d(TAG, e.toString());
			dbgUtil.fileLog(e.toString());
			return null;
		}
		catch (Exception e)
		{
			Log.d(TAG, e.toString());
			dbgUtil.fileLog(e.toString());
			return null;
		}

	}

	public static boolean NetworkIsAvailable()// Context context)
	{
		String TAG = "net_dbg@CheckNetwork";

		ConnectivityManager connManager = (ConnectivityManager) RedAntApplication
				.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
		// .getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
		if (networkInfo == null)
		{
			Log.d(TAG, "can not get Active NetworkInfo!");
			// dbgUtil.Log(Log.DEBUG, "Current Network info",
			// "can not get Active NetworkInfo!");
			return false;
		}
		NetworkInfo.State netState = networkInfo.getState();
		if (netState != NetworkInfo.State.CONNECTED)
		{
			Log.d(TAG, "not Connected!State=" + netState);
			// dbgUtil.Log(Log.DEBUG, "Current Network info",
			// "not Connected!State=" + netState);
			return false;
		}

		boolean bavailable = networkInfo.isAvailable();
		String strtype = networkInfo.getTypeName();

		Log.d(TAG, " type = " + strtype + " abailable = " + bavailable
				+ " state " + netState);

		return bavailable;
	}
	public static JSONObject Login(String user, String password) {
		String TAG = "net_dbg@Login";
		Log.d(TAG, "u:" + user + ";p:" + password);
		if (!Network.NetworkIsAvailable())
		{

			Log.d(TAG, "network not available!");
			try {
				return new JSONObject("{result:" + Network.RESULT_NET_NOTAVAILABLE+ "}");
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}


		Bundle parms = new Bundle();
		try {

			parms.putString("user", AES.encrypt("usai", user));
			parms.putString("password", AES.encrypt("usai", password));
		} catch (Exception e) {
			e.printStackTrace();
		}

		parms.putString("_operate","handset_login");
		// parms.putString("action", "handset_login");
		// int ver = ApexTrackingApplication
		// .get_instance()
		// .getSharedPreferences(name + "_Apex_auth", Context.MODE_PRIVATE)
		// .getInt("AuthInfoVer", 0);
		// parms.putString("auth_ver", ver + "");
		String jstr = getJson(RedAntApplication.active_address
				+ Network.URL_LOGIN, parms);
		/*
		 * error occur while get authorization info from server. include can not
		 * reach server , wrong parms ,server get wrong , etc.
		 */
		if (jstr == null || jstr.length() <= 0)
		{
			Log.d(TAG, "json is wrong");
			try {
				return new JSONObject("{result:" + Network.RESULT_NET_ERROR+ "}");
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
		JSONObject jsobj;
		try
		{
			jsobj = new JSONObject(jstr);
			if (jsobj.length() > 0)
			{
				return jsobj;
			}
			try {
				return new JSONObject("{result:" + Network.RESULT_NET_ERROR+ "}");
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			dbgUtil.fileLog(e.toString());
			e.printStackTrace();
//			try {
//				return new JSONObject("{result:" + Network.RESULT_NET_ERROR+ "}");
//			} catch (JSONException e1) {
//				e.printStackTrace();
//			}
			return null;
		}

//		JSONObject ret =new JSONObject();
//		ret.put("result",Network.RESULT_NET_ERROR);
		return null;
	}
	@Deprecated
	public static int VerifyUser(String user, String password)
	{
		String TAG = "net_dbg@get_Auth";
		Log.d(TAG, "u:" + user + ";p:" + password);
		if (!Network.NetworkIsAvailable())
		{
			Log.d(TAG, "network not available!");
			return Network.RESULT_NET_NOTAVAILABLE; // network not available
		}
		Bundle parms = new Bundle();
		parms.putString("user", user);
		parms.putString("password", password);
		// parms.putString("action", "handset_login");
		// int ver = ApexTrackingApplication
		// .get_instance()
		// .getSharedPreferences(name + "_Apex_auth", Context.MODE_PRIVATE)
		// .getInt("AuthInfoVer", 0);
		// parms.putString("auth_ver", ver + "");
		String jstr = getJson(RedAntApplication.active_address
				+ Network.URL_VERIFY_USER, parms);
		/*
		 * error occur while get authorization info from server. include can not
		 * reach server , wrong parms ,server get wrong , etc.
		 */
		if (jstr == null || jstr.length() <= 0)
		{
			Log.d(TAG, "json is wrong");
			return Network.RESULT_NET_ERROR;
		}
		JSONObject jsobj;
		try
		{
			jsobj = new JSONObject(jstr);
			if (jsobj.length() > 0)
			{
				int iresult = jsobj.getInt("result");
				if (iresult == Network.AP_USER_AUTH)
				{
					return RESULT_TRUE;
				}

				else
				{

					return RESULT_FALSE;
				}
			}
			return RESULT_NET_ERROR;
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			dbgUtil.fileLog(e.toString());
			e.printStackTrace();
			return RESULT_NET_ERROR;
		}

		// return parse_authinfo(jstr, name, password);
		// if(true)
		// return RESULT_TRUE;
		// String TAG = "net_dbg@VerifyUser";
		// Log.d(TAG, "entry");
		// try
		// {
		// BasicHttpParams httpParams = new BasicHttpParams();
		// HttpConnectionParams.setConnectionTimeout(httpParams,
		// REQUEST_TIMEOUT);
		// HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
		// HttpClient client = new DefaultHttpClient(httpParams);
		// HttpPost post = new HttpPost(URL_VERIFY_USER);
		// MultipartEntity reqEntity = new MultipartEntity(
		// HttpMultipartMode.BROWSER_COMPATIBLE);
		// reqEntity.addPart("user", new StringBody(user));
		// reqEntity.addPart("password", new StringBody(password));
		//
		// post.setEntity(reqEntity);
		// HttpResponse response = client.execute(post);
		// int statucode = response.getStatusLine().getStatusCode();
		// if (statucode == HttpStatus.SC_OK)
		// {
		// HttpEntity resEntity = response.getEntity();
		// if (resEntity != null)
		// {
		// Log.d(TAG,
		// "Response: content len==>"
		// + resEntity.getContentLength());
		// InputStream is = resEntity.getContent();
		// try
		// {
		//
		// BufferedReader br = new BufferedReader(
		// new InputStreamReader(is, "utf-8"), 8);
		// StringBuilder sb = new StringBuilder();
		// String line = null;
		// while ((line = br.readLine()) != null)
		// {
		// sb.append(line + "\n");
		// }
		//
		// Log.d(TAG, "Response: content begin");
		// Log.d(TAG, sb.toString());
		// Log.d(TAG, "Response: content end");
		//
		// if (sb.length()<=0)
		// {
		//
		// return RESULT_NET_ERROR;
		// }
		// JSONObject obj = new JSONObject(sb.toString());
		// if (obj.length() > 0)
		// {
		// // JSONObject obj = array.getJSONObject(0);
		// try
		// {
		// int verifyresult = Integer.parseInt(obj
		// .getString("result"));
		// if (verifyresult == Network.AP_USER_AUTH)
		// {
		// return RESULT_TRUE;
		// }
		// else
		// {
		// return RESULT_FALSE;
		// }
		// }
		// catch (Exception e)
		// {
		// Log.e(TAG, e.toString());
		// return RESULT_ERROR;
		// }
		// }
		// }
		// catch (Exception e)
		// {
		// Log.e(TAG, e.toString());
		// return RESULT_ERROR;
		// // TODO: handle exception
		// }
		// finally
		// {
		// is.close();
		//
		// }
		//
		// }
		// else
		// {
		// /*
		// * resEntity is null
		// */
		// Log.d(TAG, "RESPONSE ENTITY IS NULL");
		// return RESULT_NET_ERROR;
		// }
		//
		// }
		// else
		// {
		// /*
		// * Http error; out put error code;
		// */
		// Log.d(TAG, "HTTP " + statucode);
		//
		// HttpEntity resEntity = response.getEntity();
		// if (resEntity != null)
		// {
		//
		// InputStream is = resEntity.getContent();
		// try
		// {
		//
		// BufferedReader br = new BufferedReader(
		// new InputStreamReader(is, "utf-8"), 8);
		// StringBuilder sb = new StringBuilder();
		// String line = null;
		// while ((line = br.readLine()) != null)
		// {
		// sb.append(line + "\n");
		// }
		//
		// Log.d(TAG, "Response: content begin");
		// Log.d(TAG, sb.toString());
		// Log.d(TAG, "Response: content end");
		// return RESULT_ERROR;
		// }
		// catch (Exception e)
		// {
		// Log.e(TAG, e.toString());
		// return RESULT_ERROR;
		// // TODO: handle exception
		// }
		// finally
		// {
		// is.close();
		//
		// }
		//
		// }
		// else
		// {
		// /*
		// * resEntity is null
		// */
		// Log.e(TAG, "RESPONSE ENTITY IS NULL");
		// return RESULT_NET_ERROR;
		// }
		// }
		//
		// }
		// catch (ConnectTimeoutException e)
		// {
		// Log.d(TAG, "request time out");
		// return RESULT_NET_ERROR;
		//
		// }
		// catch (Exception e)
		// {
		// Log.d(TAG, e.toString());
		// return RESULT_ERROR;
		// }
		// return RESULT_ERROR;
	}
	public static JSONObject UploadImage(String path, Bundle Params,String server,FileUploadListener listener)
	{
		String TAG = "net_dbg@UploadImage";
		Bitmap source = BitmapFactory.decodeFile(path);

		int originWidth = source.getWidth();
		int originHeight = source.getHeight();

		int width = originWidth, height = originHeight;

		if (originHeight > 1024 || originWidth > 1024)
		{
			if (originWidth > originHeight)
			{
				width = 1024;
				height = originHeight * 1024 / originWidth;

			}
			else
			{

				height = 1024;
				width = originWidth * 1024 / originHeight;

			}
		}
		Bitmap scaled = Bitmap.createScaledBitmap(source, width, height, true);
		OutputStream fOutputStream = null;
		String scaledPath = path.replace(".jpg", "_scaled.jpg");
//		File file = new File(scaledPath);
//		try
//		{
//			fOutputStream = new FileOutputStream(file);
//
//			scaled.compress(Bitmap.CompressFormat.JPEG, 95, fOutputStream);
//
//			fOutputStream.flush();
//			fOutputStream.close();
//
//			// MediaStore.Images.Media.insertImage(RedAntApplication.getInstance().getContentResolver(),
//			// file.getAbsolutePath(), file.getName(), file.getName());
//		}
//		catch (FileNotFoundException e)
//		{
//			e.printStackTrace();
//
//			dbgUtil.fileLog(e.toString());
//			return RESULT_LOCALFILE_ERROR;
//		}
//		catch (IOException e)
//		{
//			e.printStackTrace();
//
//			dbgUtil.fileLog(e.toString());
//			return RESULT_LOCALFILE_ERROR;
//		}
		String jstr = UploadFile(path,server, Params,listener);
//		file.delete();
		if (jstr == null || jstr.length() <= 0)
		{
			Log.d(TAG, "json is wrong");
			try {
				return new JSONObject("{result:" + Network.RESULT_NET_ERROR+ "}");
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
		JSONObject jsobj;
		try
		{
			jsobj = new JSONObject(jstr);
			if (jsobj.length() > 0)
			{
				return jsobj;
			}
			try {
				return new JSONObject("{result:" + Network.RESULT_NET_ERROR+ "}");
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			dbgUtil.fileLog(e.toString());
			e.printStackTrace();
//			try {
//				return new JSONObject("{result:" + Network.RESULT_NET_ERROR+ "}");
//			} catch (JSONException e1) {
//				e.printStackTrace();
//			}
			return null;
		}
		return null;
	}
	@Deprecated
	public static int UploadImage(String path, String user, String password,
			String pid,String server)
	{

		Bitmap source = BitmapFactory.decodeFile(path);

		int originWidth = source.getWidth();
		int originHeight = source.getHeight();

		int width = originWidth, height = originHeight;

		if (originHeight > 1024 || originWidth > 1024)
		{
			if (originWidth > originHeight)
			{
				width = 1024;
				height = originHeight * 1024 / originWidth;

			}
			else
			{

				height = 1024;
				width = originWidth * 1024 / originHeight;

			}
		}
		Bitmap scaled = Bitmap.createScaledBitmap(source, width, height, true);
		OutputStream fOutputStream = null;
		String scaledPath = path.replace(".jpg", "_scaled.jpg");
		File file = new File(scaledPath);
		try
		{
			fOutputStream = new FileOutputStream(file);

			scaled.compress(Bitmap.CompressFormat.JPEG, 95, fOutputStream);

			fOutputStream.flush();
			fOutputStream.close();

			// MediaStore.Images.Media.insertImage(RedAntApplication.getInstance().getContentResolver(),
			// file.getAbsolutePath(), file.getName(), file.getName());
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();

			dbgUtil.fileLog(e.toString());
			return RESULT_LOCALFILE_ERROR;
		}
		catch (IOException e)
		{
			e.printStackTrace();

			dbgUtil.fileLog(e.toString());
			return RESULT_LOCALFILE_ERROR;
		}
		int ret = UploadFiled  (scaledPath, user, password, pid,server);
		file.delete();
		return ret;

	}
	public static String UploadFile(String path ,String host,Bundle params,FileUploadListener listener){


		File file = new File(path);
		String TAG = "net_dbg@UploadFile";
		   String CHARSET = "utf-8"; //设置编码
		   String PREFIX = "--";
		   String LINE_END = "\r\n";
		String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n";
		String CONTENT_TYPE = "multipart/form-data"; //内容类型
		try {
			URL url = new URL(host);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(SO_TIMEOUT);
			conn.setConnectTimeout(SO_TIMEOUT);
			conn.setRequestMethod("POST"); //请求方式
			conn.setRequestProperty("Charset", "utf-8");//设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
			conn.setDoInput(true); //允许输入流
			conn.setDoOutput(true); //允许输出流
			conn.setUseCaches(false); //不允许使用缓存
			if(file!=null) {
				/** * 当文件不为空，把文件包装并且上传 */
				OutputStream outputSteam=conn.getOutputStream();
				DataOutputStream dos = new DataOutputStream(outputSteam);
				StringBuffer sb = new StringBuffer();
				sb.append(LINE_END);
				if(params!=null){//根据格式，开始拼接文本参数


					Set<String> keys = params.keySet();
					Log.d(TAG, "================parms============");
					for (String key : keys)
					{

						sb.append(PREFIX).append(BOUNDARY).append(LINE_END);//分界符
						sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + LINE_END);
						sb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END);
						sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
						sb.append(LINE_END);
						sb.append(params.get(key).toString());
						sb.append(LINE_END);//换行！

//					connection.setRequestProperty(key, parms.get(key).toString());
							Log.d(TAG, "key=" + key + "    val="
									+ params.get(key).toString());

//					reqEntity.addPart(key, new StringBody());

					}



				}
				sb.append(PREFIX);//开始拼接文件参数
				sb.append(BOUNDARY); sb.append(LINE_END);
				/**
				 * 这里重点注意：
				 * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字，包含后缀名的 比如:abc.png
				 */
				sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
				sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
				sb.append(LINE_END);
				//写入文件数据
				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				long totalbytes = file.length();
				long curbytes = 0;
				Log.i("cky","total="+totalbytes);
				int len = 0;
				while((len=is.read(bytes))!=-1){
					curbytes += len;
					dos.write(bytes, 0, len);
					listener.onProgress(curbytes,1.0d*curbytes/totalbytes);
				}
				is.close();
				dos.write(LINE_END.getBytes());//一定还有换行
				byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功
				 * 当响应成功，获取响应的流
				 */
				int code = conn.getResponseCode();
				sb.setLength(0);
				BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line;
				while((line=br.readLine())!=null){
					sb.append(line);
				}
				listener.onFinish(code,sb.toString()/*,conn.getHeaderFields()*/);
				return sb.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public interface FileUploadListener {
		void onProgress(long pro, double percentage);

		void onFinish(int code, String res/*, HashMap<String, List<String>> headers*/);
	}

	@Deprecated
	public static int UploadFiled(String path, String user, String password,
			String pid,String server)
	{
		String TAG = "net_dbg@UploadFile";
		Log.d(TAG, "entry");

		Log.d(TAG, "sourcefile:" + path);
		File file = new File(path);

		if (file.exists() == false)
		{
			dbgUtil.fileLog("file "+ path +" not found!");
			return RESULT_LOCALFILE_ERROR;
		}
		String md5 = MD5.md5sum(path);
		Log.d(TAG, "MD5:" + md5);
		if (md5 == null)
		{
			Log.d(TAG, "md5 sum failed");
			dbgUtil.fileLog("md5 sum failed");
			return RESULT_LOCALFILE_ERROR;

		}
		try
		{
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
			HttpClient client = new DefaultHttpClient(httpParams);
			HttpPost post = new HttpPost(server
					+ URL_UPLOAD_PHOTO);
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			reqEntity.addPart("user", new StringBody(user));
			reqEntity.addPart("password", new StringBody(password));
			reqEntity.addPart("pid", new StringBody(pid));
			reqEntity.addPart("md5", new StringBody(md5));

			FileBody bin = new FileBody(file);
			reqEntity.addPart("imagefile", bin);
			post.setEntity(reqEntity);
			HttpResponse response = client.execute(post);
			int statucode = response.getStatusLine().getStatusCode();
			if (statucode == HttpStatus.SC_OK)
			{
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null)
				{
					Log.d(TAG,
							"Response: content len==>"
									+ resEntity.getContentLength());
					InputStream is = resEntity.getContent();
					try
					{

						BufferedReader br = new BufferedReader(
								new InputStreamReader(is, "utf-8"), 8);
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = br.readLine()) != null)
						{
							sb.append(line + "\n");
						}

						Log.d(TAG, "Response: content begin");
						Log.d(TAG, sb.toString());
						Log.d(TAG, "Response: content end");

						if (sb.length() <= 0)
						{

							return RESULT_NET_ERROR;
						}
						JSONObject obj = new JSONObject(sb.toString());
						if (obj.length() > 0)
						{
							// JSONObject obj = array.getJSONObject(0);
							try
							{
								int uploadresult = Integer.parseInt(obj
										.getString("result"));
								if (uploadresult == Network.AP_UPLOAD_SUCCESS)
								{
									return RESULT_TRUE;
								}
								else if (uploadresult == Network.AP_USER_NOT_AUTH)
								{
									Log.d(TAG, "RESULT_ERR_USERAUTH");
									return RESULT_USERAUTH_ERROR;
								}
								else
								{
									return RESULT_FALSE;
								}
							}
							catch (Exception e)
							{
								Log.e(TAG, e.toString()+1);
								dbgUtil.fileLog(e.toString());
								return RESULT_FALSE;
							}
						}
					}
					catch (Exception e)
					{
						Log.e(TAG, e.toString());
						dbgUtil.fileLog(e.toString());
						return RESULT_NET_ERROR;
						// TODO: handle exception
					}
					finally
					{
						is.close();

					}

				}
				else
				{
					/*
					 * resEntity is null
					 */
					Log.d(TAG, "RESPONSE ENTITY IS NULL");
					return RESULT_NET_ERROR;
				}

			}
			else
			{
				/*
				 * Http error; out put error code;
				 */
				Log.d(TAG, "HTTP " + statucode);

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null)
				{

					InputStream is = resEntity.getContent();
					try
					{

						BufferedReader br = new BufferedReader(
								new InputStreamReader(is, "utf-8"), 8);
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = br.readLine()) != null)
						{
							sb.append(line + "\n");
						}

						Log.d(TAG, "Response: content begin");
						Log.d(TAG, sb.toString());
						Log.d(TAG, "Response: content end");
						return RESULT_NET_ERROR;
					}
					catch (Exception e)
					{
						Log.e(TAG, e.toString());
						dbgUtil.fileLog(e.toString());
						return RESULT_NET_ERROR;
						
						// TODO: handle exception
					}
					finally
					{
						is.close();

					}

				}
				else
				{
					/*
					 * resEntity is null
					 */
					Log.e(TAG, "RESPONSE ENTITY IS NULL");
					return RESULT_NET_ERROR;
				}
			}

		}
		catch (ConnectTimeoutException e)
		{
			Log.d(TAG, "request time out");
			dbgUtil.fileLog(e.toString());
			return RESULT_NET_ERROR;

		}
		catch (SocketTimeoutException e)
		{
			Log.d(TAG, "socket time out");
			dbgUtil.fileLog(e.toString());
			return RESULT_NET_ERROR;
		}
		catch (UnknownHostException e)
		{
			Log.d(TAG, e.toString());
			dbgUtil.fileLog(e.toString());
			return RESULT_NET_ERROR;
		}
		catch (HttpHostConnectException e)
		{
			Log.d(TAG, e.toString());
			dbgUtil.fileLog(e.toString());
			return RESULT_NET_ERROR;
		}
		catch (Exception e)
		{
			Log.d(TAG, e.toString()+" RESULT_ERROR!!");
			dbgUtil.fileLog(e.toString());
			return RESULT_ERROR;
		}

		return RESULT_FALSE;

		// try
		// {
		// HttpClient client = new DefaultHttpClient();
		// HttpPost post = new HttpPost(url);
		// MultipartEntity reqEntity = new MultipartEntity(
		// HttpMultipartMode.BROWSER_COMPATIBLE);
		// reqEntity.addPart("user", new StringBody(user));
		// reqEntity.addPart("password", new StringBody(password));
		// reqEntity.addPart("pid", new StringBody(pid));
		// FileBody bin = new FileBody(file);
		// reqEntity.addPart("imagefile", bin);
		// post.setEntity(reqEntity);
		// HttpResponse response = client.execute(post);
		// HttpEntity resEntity = response.getEntity();
		// if (resEntity != null)
		// {
		//
		// String result = EntityUtils.toString(resEntity);
		// Log.d(TAG, "Response:" + result);
		// return Integer.parseInt(result);
		// // if(Boolean.parseBoolean(result)==true)
		// // return true;
		// // else
		// // return false;
		// }
		//
		// }
		// catch (Exception e)
		// {
		// e.printStackTrace();
		// }
		// return 0;
	}

	public static boolean NetworkIsAvailable(Context context)
	{
		String TAG = "net_dbg@CheckNetwork";
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
		if (networkInfo == null)
		{
			Log.d(TAG, "can not get Active NetworkInfo!");
			// dbgUtil.Log(Log.DEBUG, "Current Network info",
			// "can not get Active NetworkInfo!");
			return false;
		}
		NetworkInfo.State netState = networkInfo.getState();
		if (netState != NetworkInfo.State.CONNECTED)
		{
			Log.d(TAG, "not Connected!State=" + netState);
			// dbgUtil.Log(Log.DEBUG, "Current Network info",
			// "not Connected!State=" + netState);
			return false;
		}
		// int iconntype = -1;
		// iconntype = networkInfo.getType();

		// boolean bUseMobileNetwork = context.getSharedPreferences(
		// "PhoneAsstPref", 0).getBoolean("UseMobileNetwork", false);
		//
		// if (bUseMobileNetwork == false
		// && iconntype != ConnectivityManager.TYPE_WIFI && iconntype != 9/*
		// earthnet */)
		// {
		// Log.d(TAG,);
		// dbgUtil.Log(Log.DEBUG, "Current Network info",
		// "not allowed!Connection type=" + networkInfo.getTypeName());
		// return false;
		// }
		boolean bavailable = networkInfo.isAvailable();
		String strtype = networkInfo.getTypeName();

		Log.d(TAG, " type = " + strtype + " abailable = " + bavailable
				+ " state " + netState);
		// dbgUtil.Log(Log.INFO, "Current Network info", " type = " + strtype
		// + " abailable = " + bavailable + " state " + netState);
		return bavailable;
	}

	public static Bitmap getImageFromLink(String link) {
		HttpURLConnection connection = null;
		Bitmap img = null;
		try {

			URL url = new URL(link);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("GET");
			img = BitmapFactory.decodeStream(connection.getInputStream());

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return img;
	}
}
