package com.eactive.eai.adapter.http.dynamic.impl;

import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Properties;

public class HttpAdapterServicePass extends HttpAdapterServiceSupport {
	static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
	private static final int BUFFER_SIZE = 1024;
	private static final String FROM = "From";
	private static final String FILE_TYPE = "FileType";
	private static final String FILE_NAME = "FileName";
	private static final String USER_AGENT = "User-Agent";
	private static final String USER_HEADER = "User-Header";
	private static final String CONTENT_TYPE = "Content-Type";

	public void service(String adptGrpName, String adptName, HttpServletRequest request, HttpServletResponse response) {

		PropManager manager = PropManager.getInstance();

		Properties prop = manager.getProperties("BYPASS_REU");
		String url = prop.getProperty("URL", "http://192.168.12.224:8068/ForexWeb/ForexServiceServlet");
		int connectionTimeout = 30000;
		int timeout = 30000;

		if (prop != null) {
			try {
				connectionTimeout = Integer.parseInt(prop.getProperty("CONNECTION_TIMEOUT", "30000"));
			} catch (NumberFormatException e) {
				connectionTimeout = 30000;
			}
			try {
				timeout = Integer.parseInt(prop.getProperty("TIMEOUT", "30000"));
			} catch (NumberFormatException e) {
				timeout = 30000;
			}
		}

		String from = request.getHeader(FROM);
		String fileType = request.getHeader(FILE_TYPE);
		String fileName = request.getHeader(FILE_NAME);
		String userAgent = request.getHeader(USER_AGENT);// "Forex HTTP Connector"
		String userHeader = request.getHeader(USER_HEADER);
		String contentType = request.getHeader(CONTENT_TYPE);// "text/plain"
		ByteArrayOutputStream outStream = null;
		DataInputStream inStream = null;
		byte[] data = null;

		try {
			int c = -1;
			byte[] bytes = new byte[BUFFER_SIZE];
			inStream = new DataInputStream(request.getInputStream());
			outStream = new ByteArrayOutputStream();

			while ((c = inStream.read(bytes, 0, bytes.length)) != -1) {
				outStream.write(bytes, 0, c);
			}
			data = new byte[outStream.toByteArray().length];
			data = outStream.toByteArray();
		} catch (IOException e1) {
			if (logger.isError())
				logger.error("HttpPassAdapter] IOException ", e1);
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
			} catch (Exception e) {
				logger.warn(e);
			}
			try {
				if (outStream != null) {
					outStream.close();
				}
			} catch (Exception e) {
				logger.warn(e);
			}
		}

		HttpClient httpClient = new HttpClient();
		
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
		
		PostMethod post = new PostMethod(url);

		post.setRequestHeader(FROM, from);
		post.setRequestHeader(FILE_TYPE, fileType);
		post.setRequestHeader(FILE_NAME, fileName);
		post.setRequestHeader(USER_AGENT, userAgent);
		post.setRequestHeader(USER_HEADER, userHeader);
		post.setRequestHeader(CONTENT_TYPE, contentType);

//		post.setRequestBody(new ByteArrayInputStream(data));
//		if (data != null) {
//			post.setRequestContentLength(data.length);
//		}
		ByteArrayRequestEntity entity = new ByteArrayRequestEntity(data);
		post.setRequestEntity(entity);

		int status = -1;

		try {
			status = httpClient.executeMethod(post);
		} catch (SocketTimeoutException ste) {
			if (logger.isError()) {
				logger.error("HttpPassAdapter] SocketTimeoutException : " + ste.toString(), ste);
			}
		} catch (ConnectException ce) {
			if (logger.isError()) {
				logger.error("HttpPassAdapter] Connection Exception : " + ce.toString(), ce);
			}
		} catch (Exception e) {
			if (logger.isError()) {
				logger.error("HttpPassAdapter] Exception : " + e.toString(), e);
			}
		} finally {
			post.releaseConnection();
			if (status != HttpStatus.SC_OK) {
				logger.error("Http error status=" + status);				
			}
		}
		response.setContentType("text/html");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.print(post.getResponseBodyAsString());
		} catch (IOException e) {
			if (logger.isError()) {
				logger.error("HttpPassAdapter] IOException : " + e.toString(), e);
			}
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (Exception e) {
				logger.warn(e);
			}
		}
	}
}
