package org.gcube.nlphub.legacy;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.gcube.nlphub.nlp.NlpParameter;

public class AsyncHttpRequest extends Thread {
	private String baseUrl, finalUrl, result, method;
	private ArrayList<NlpParameter> parameters;
	private Logger logger = Logger.getLogger(AsyncHttpRequest.class.getSimpleName());
	protected long elapsedTime;

	public AsyncHttpRequest() {
		this.baseUrl = null;
		this.parameters = null;
		this.method = "GET";
		finalUrl = null;
		elapsedTime = 0; 
	}
	
	public AsyncHttpRequest(String baseUrl, String method, ArrayList<NlpParameter> parameters) {
		this.baseUrl = baseUrl;
		this.parameters = parameters;
		if(method == null)
			this.method = "GET";
		else
			this.method = (method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("POST")) ? method : "GET";
		setFinalUrl();
		elapsedTime = 0;
	}

	public void run() {
		elapsedTime = System.currentTimeMillis();
		if(finalUrl == null)
			finalUrl = baseUrl;
		HttpURLConnection connection = null;
		BufferedReader r = null;
		try {
			URL url = new URL(finalUrl);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(method);
			r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = "";
			result = "";

			while (line != null) {
				line = r.readLine();
				if (line != null)
					result += line.trim();
			}
			
			asyncHttpRequestCallback();

		} catch (Exception x) {
			logger.error(x.getLocalizedMessage());
			asyncHttpRequestCallback();
		} finally {
			try {
				if (r != null)
					r.close();
				if (connection != null)
					connection.disconnect();
			} catch (Exception e) {
				logger.error(e.getLocalizedMessage());
			}
		}
	}
	
	public String getResult() {
		return result;
	}
	
	public void asyncHttpRequestCallback() {
		elapsedTime = System.currentTimeMillis() - elapsedTime;
	}
	
	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public void setParameters(ArrayList<NlpParameter> parameters) {
		this.parameters = parameters;
	}

	private void setFinalUrl() {
		finalUrl = baseUrl;
		if (parameters != null) {
			if (finalUrl.indexOf("?") < 0)
				finalUrl += "?";
			for (NlpParameter p : parameters) {
				try {
					finalUrl += p.getName() + "=" + URLEncoder.encode((String) p.getValue(), "UTF-8");
					finalUrl += "&";
				} catch (Exception x) {
					logger.error(x.getLocalizedMessage());
				}
			}
			finalUrl = finalUrl.substring(0, finalUrl.length() - 1);
		}
	}
}
