package com.usai.util;

import java.io.BufferedReader;
import java.io.File;
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.net.Socket;
import java.net.SocketTimeoutException;
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.Set;

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.photo.RedAntApplication;

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

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

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						= -1;
	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";
	static String				URL_VERIFY_USER					= "handset_login.php";

	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, UnknownHostException
		{
			return sslContext.getSocketFactory().createSocket(socket, host,
					port, autoClose);
		}

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

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

	public static String getJson(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 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 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 = UploadFile(scaledPath, user, password, pid,server);
		file.delete();
		return ret;

	}

	public static int UploadFile(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;
	}

}
