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

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Properties;

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 com.eactive.eai.adapter.http.HttpMemoryLogger;
import com.eactive.eai.adapter.http.HttpStatusException;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceSupport;
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
import com.eactive.eai.common.exception.ExceptionUtil;

public class HttpClientAdapterServiceSoap extends HttpClientAdapterServiceSupport {

	public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {

		HttpClientAdapterVO vo = super.setting(prop, tempProp);
		String soapAction = prop.getProperty(METHOD_SOAP_ACTION);
		if (soapAction != null)
			soapAction = soapAction.trim();

		if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
			logger.debug("HttpClientAdapter] SEND (" + vo.getMethod() + ") ");
		}
		PostMethod method = new PostMethod(vo.getUrl());
		if (vo.getTimeout() > -1) {
			method.getParams().setSoTimeout(vo.getTimeout());
		}
		HttpClient mclient = this.client;

		byte[] sendBytes = null;
		if (data instanceof String) {
			sendBytes = ((String) data).getBytes(vo.getEncode());
		} else if (data instanceof byte[]) {
			sendBytes = (byte[]) data;
		}
		ByteArrayRequestEntity entity = new ByteArrayRequestEntity(sendBytes);

		method.setRequestEntity(entity);
		method.setRequestHeader("SOAPAction", soapAction);

		int status = -1;
		
		configureHttpClient(mclient, method, vo, vo.getUrl(), vo.getContentType());
		
		try {
			status = mclient.executeMethod(method);
			// status 200(정상) 이외에는 error 처리
			if (status != 200) {
				try {
					logger.error("HttpClientAdapterServiceSoap] receive status[" + status + "] data["
							+ new String(method.getResponseBody()) + "]");
				} catch (Exception e) {
					logger.error(e);
				}
				throw new HttpStatusException("수신시스템을 확인하세요. HTTP 에러[ " + status + "] adapterName="
						+ vo.getAdapterGroupName() + "." + vo.getAdapterName(), status);
			}
			byte[] responseMessage = method.getResponseBody();
			return responseMessage;

			// return removeSoap(responseMessage,function).getBytes();

		} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
						"HttpClientAdapterServiceSoap] SocketTimeoutException : " + ste.toString(), ste);
			}
			if (logger.isError()) {
				logger.error("HttpClientAdapterServiceSoap] SocketTimeoutException : " + ste.toString(), ste);
			}
			throw ste;
		} catch (ConnectException ce) {
			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
						"HttpClientAdapterServiceSoap] Connection Exception : " + ce.toString(), ce);
			}
			if (logger.isError()) {
				logger.error("HttpClientAdapterServiceSoap] Connection Exception : " + ce.toString(), ce);
			}
			throw ce;
		} catch (Exception e) {
			if (vo.getTraceLevel() >= 3) {
				HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
						"HttpClientAdapterServiceSoap] Exception : " + e.toString(), e);
			}
			if (logger.isError()) {
				logger.error("HttpClientAdapterServiceSoap] Exception : " + e.toString(), e);
			}
			throw e;
		} finally {
			method.releaseConnection();
			if (status != HttpStatus.SC_OK) {
				String[] msgArgs = new String[1];
				msgArgs[0] = String.valueOf(status);
				String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
				if (logger.isDebug()) {
					logger.debug(resMsg);
				}
			}
		}

	}
//    private String addSoap(String message) throws Exception {
//     	StringBuffer sb = new StringBuffer();
//     	sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");
//     	sb.append("<soapenv:Body>");
//     	sb.append(message);
//     	sb.append("</soapenv:Body>");
//     	sb.append("</soapenv:Envelope>");   
//     	return sb.toString();
//     }
//     private String getFunction(String message) throws Exception {
//     	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
//     	dbFactory.setIgnoringElementContentWhitespace(true);
//     	DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
//     	Document doc = docBuilder.parse(new InputSource(new StringReader(message.trim())));			
//     	return doc.getDocumentElement().getNodeName();
//     }        
//     private String removeSoap(String result,String function) throws Exception {
//     	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
//     	dbFactory.setIgnoringElementContentWhitespace(true);
//     	DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
//     	Document doc = docBuilder.parse(new InputSource(new StringReader(result.trim())));			
//     	NodeList nodes = doc.getElementsByTagName(function + "Return");
//     	return nodes.item(0).getFirstChild().getNodeValue();
//     }

}
