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

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.InboundErrorLogger;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.UUIDGenerator;
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
import com.eactive.eai.inbound.error.InboundErrorKeys;
import com.eactive.eai.util.HexaConverter;

public class UnknownMessageLogUtils {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private UnknownMessageLogUtils() {
		throw new IllegalStateException("Utility class");
	}
	
	public static void logUnkownMessage(String adptGrpName, String adptName, Object message, Properties prop,
			HttpServletRequest request, HttpServletResponse response, String errCode, Exception e) {
		try {
			EAIServerManager eaiServerManager = EAIServerManager.getInstance();
	        String serverName = eaiServerManager.getLocalServerName();
	        String txId = prop.getProperty(HttpClientAdapterServiceKey.TRANSACTION_ID);
	        if(StringUtils.isEmpty(txId)) {
	        	StringBuffer sb = new StringBuffer();
	            
	            String instanceid1 = serverName.substring(0,2);
	            String instanceid2 = serverName.substring(serverName.length()-2, serverName.length());
	            String instid = instanceid1 + instanceid2;
	            txId = instid + UUIDGenerator.getUUID();
	        }
	        String clientId = prop.getProperty("clientId");
	        String hexClientId = clientId != null ? HexaConverter.bytesToHexa(clientId.getBytes()) : "";
			String errorMsg = ExceptionUtil.make(e, errCode);
			StringBuffer sb = new StringBuffer();
			sb.append(errorMsg).append("\n").append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
	                .append(request.getRequestURI()).append("\n").append("clientId=").append(clientId).append(",hexClientId=").append(hexClientId).append(",txProp=").append(prop).append("\n").append("Exception : ").append(e.getMessage());
			UnknownMessageLogUtils.logUnknownMessage(txId, adptGrpName, adptName, 
					"", "", false, errCode, sb.toString(), System.currentTimeMillis(),
					serverName, InboundErrorKeys.IN_UNKNOWN, message);
		} catch (Exception ex) {
			logger.warn("unkown log fail.", ex);
		}
		
	}

//	public static void logUnkownMessage(String uuid, String adapterGroupName, String adapterName, String errCode,
//			String errMsg, Object message) {
//		UnkownMessageLogUtils.logUnknownMessage(uuid, adapterGroupName, adapterName, 
//				"", "", false, errCode, errMsg, System.currentTimeMillis(),
//				EAIServerManager.getInstance().getInstId(), InboundErrorKeys.IN_UNKNOWN, message);
//	}
	
	private static void logUnknownMessage(String uuid, String adapterGroupName, String adapterName,
			String bzwkSvcKeyName, String eaiSvcCd, boolean isTasStarted, String errCode, String errMsg, long errTm,
			String svcInstNm, String errDstCd, Object message) {
		String msg = null;
		
		if(errDstCd == null || errDstCd.length() ==0) {
			errDstCd = "ND";
		}
		
		if(isTasStarted) {
			errDstCd = InboundErrorKeys.TAS_START;
		}
		
		InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
		errorInfoVO.setEaiSvcSno(uuid);                     // EAI서비스일련번호
		errorInfoVO.setAdptBwkGrpNm(adapterGroupName);      // 어댑터업무그룹명
		errorInfoVO.setEaiSvcCd(eaiSvcCd);
		errorInfoVO.setErrCd(errCode);                           // 에러코드
		errorInfoVO.setErrTxt(errMsg);                          // 에러내용
		errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(errTm));                           // 에러발생시각
		errorInfoVO.setErrDstcd(errDstCd);
		errorInfoVO.setBzwkSvcKeyName(bzwkSvcKeyName);
		
		if(message == null) {
			msg = "null";
		}
		else {
			if(message instanceof byte[]) {
				AdapterManager adapterManager = AdapterManager.getInstance();
		        AdapterGroupVO srcAdapterGrpVO = adapterManager.getAdapterGroupVO(adapterGroupName);
		        
		        // TAS 거래일 경우 NULL일 수 있음
		        if(srcAdapterGrpVO == null) {
		        	msg = new String((byte[])message);
		        }
		        else {
//			        String srcAdapterMsgType = srcAdapterGrpVO.getMessageType();
//			        if( MessageUtil.isUTF8(srcAdapterMsgType) ) {
//			        	try {
//							msg = new String((byte[])message, UJSONMessage.encode);
//						} catch (UnsupportedEncodingException e) {
//							logger.warn("msg encode error", e);
//							msg = new String((byte[])message);					}
//			        }
//			        else {
//			        	msg = new String((byte[])message);
//			        }
		        	
		        	String charset = StringUtils.defaultIfBlank(srcAdapterGrpVO.getMessageEncode(), Charset.defaultCharset().name());
		        	try {
						msg = new String((byte[])message, charset);
					} catch (UnsupportedEncodingException e) {
						logger.warn("msg encode error", e);
						msg = new String((byte[])message);
					}
		        }
		        
			}
			else if(message instanceof String) {
				msg = (String)message;
			}
			else {
				msg = "invaild message ["+message.getClass().getName()+"] "+message.toString();
			}
		}
		
		errorInfoVO.setBwkDataTxt(msg);                      // 업무데이터내용
		errorInfoVO.setEaiSvrInstNm(svcInstNm);                    // EAI서버인스턴스명
		
		InboundErrorLogger.error(errorInfoVO);
		
		if (logger.isError()) {
			logger.error("======================================================================" );
			logger.error(" RequestDispatcher] GET UNKNOWN MESSAGE");
			logger.error(" ADAPTER GROUP NAME [" + adapterGroupName + "]");
			logger.error(" EAISVCNAME [" + eaiSvcCd + "]");
			logger.error(" ADAPTER NAME [" + adapterName + "]");
			logger.error("======================================================================" );
		}    
		
	}
}
