package com.growthbeat.http;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import android.os.Build;

import com.growthbeat.GrowthbeatException;

public class BaseHttpClient {

	public enum RequestMethod {
		GET, POST, PUT, DELETE
	}

	private String baseUrl = null;
	private int connectionTimeout = 60 * 1000;
	private int socketTimeout = 60 * 1000;

	public BaseHttpClient() {
		super();
	}

	public BaseHttpClient(String baseUrl, int connectionTimeout, int socketTimeout) {
		this();
		setBaseUrl(baseUrl);
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public int getConnectionTimeout() {
		return connectionTimeout;
	}

	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	public int getSocketTimeout() {
		return socketTimeout;
	}

	public void setSocketTimeout(int socketTimeout) {
		this.socketTimeout = socketTimeout;
	}

	public String request(RequestMethod requestMethod, String path, Map<String, Object> parameters) {

		String query = "?";
		for (Entry<String, Object> parameter : parameters.entrySet())
			query += parameter.getKey() + "=" + parameter.getValue() + "&";
		try {
			query = URLEncoder.encode(query.substring(0, query.length() - 1), "UTF-8");
		} catch (UnsupportedEncodingException e) {
		}

		String url = String.format("%s%s", baseUrl, path);

		return request(requestMethod, url, query);

	}

	protected String request(RequestMethod requestMethod, String urlString, String query) {

		String response = null;
		HttpURLConnection httpURLConnection = generateHttpURLConnection(requestMethod, urlString, query);
		InputStream inputStream = null;

		try {
			httpURLConnection.connect();

			if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
				throw new GrowthbeatException(httpURLConnection.getResponseMessage());
			} else {
				inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
				String line = "";
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
				StringBuilder stringBuilder = new StringBuilder();

				while ((line = bufferedReader.readLine()) != null) {
					stringBuilder.append(line);
				}

				bufferedReader.close();
				response = stringBuilder.toString();
			}
		} catch (IOException e) {
			throw new GrowthbeatException("Failed to connection. " + e.getMessage(), e);
		} finally {
			if (inputStream != null)
				try {
					inputStream.close();
				} catch (IOException e) {
					throw new GrowthbeatException("Failed to close connection. " + e.getMessage(), e);
				}
			httpURLConnection.disconnect();
		}

		return response;

	}

	private HttpURLConnection generateHttpURLConnection(RequestMethod requestMethod, String urlString, String query) {

		try {

			if (requestMethod == RequestMethod.GET && query != null && query.length() > 0)
				urlString += query;

			URL url = new URL(urlString);

			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
				System.setProperty("http.keepAlive", "false");
			}

			if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2 && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
				httpURLConnection.setRequestProperty("Connection", "close");
			}

			httpURLConnection.setConnectTimeout(getConnectionTimeout());
			httpURLConnection.setRequestMethod(requestMethod.toString());
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpURLConnection.setRequestProperty("Accept", "application/json");

			if (requestMethod != RequestMethod.GET) {
				httpURLConnection.setDoOutput(true);
				httpURLConnection.setDoInput(true);

				if (query != null) {
					OutputStream outputStream = httpURLConnection.getOutputStream();
					outputStream.write(query.getBytes());
					outputStream.flush();
					outputStream.close();
				}
			}

			return httpURLConnection;

		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}

		throw new GrowthbeatException("Failed create HttpURLConnection");

	}

}

@@ -529,16 +529,73 @@
 ient %7B%0A%0A
+%09private static final String CONTENT_CHARSET = %22UTF-8%22;%0A%0A
 %09public 
@@ -1500,10 +1500,54 @@
 y = 
+(requestMethod == RequestMethod.GET) ? %22?%22 : 
 %22
-?
 %22;%0A%09
@@ -1608,17 +1608,29 @@
 rySet())
-%0A
+ %7B%0A%09%09%09try %7B%0A%09
 %09%09%09query
@@ -1664,125 +1664,84 @@
 %22 + 
-parameter.getValue() + %22&%22;%0A%09%09try %7B%0A%09%09%09query = URLEncoder.encode(query.substring(0, query.length() - 1), %22UTF-8%22)
+URLEncoder.encode((String) parameter.getValue(), CONTENT_CHARSET) + %22&%22
 ;%0A%09%09
+%09
 %7D ca
@@ -1777,25 +1777,80 @@
 tion e) %7B%0A%09%09
-%7D
+%09%7D%0A%09%09%7D%0A%09%09query = query.substring(0, query.length() - 1);
 %0A%0A%09%09String u
@@ -2588,23 +2588,31 @@
 Stream, 
-%22UTF-8%22
+CONTENT_CHARSET
 ));%0A%09%09%09%09
@@ -4098,22 +4098,35 @@
 charset=
-UTF-8%22
+%22 + CONTENT_CHARSET
 );%0A%09%09%09ht
@@ -4453,16 +4453,31 @@
 etBytes(
+CONTENT_CHARSET
 ));%0A%09%09%09%09

fix query building