package com.eactive.eai.flowcontroller;

import java.util.Iterator;
import java.util.Properties;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.adapter.Keys;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.common.EAIKeys;
import com.eactive.eai.common.EAITable;
import com.eactive.eai.common.exception.ExceptionHandler;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.routing.IFRouter;
import com.eactive.eai.common.routing.Process;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.common.util.ServiceUtil;
import com.eactive.eai.control.LogSender;
import com.eactive.eai.message.StandardMessage;
import com.eactive.eai.message.service.InterfaceMapper;
import com.eactive.eai.transformer.function.util.CodeConversion;
import com.ext.eai.common.stdmessage.STDMessageKeys;

public class PubFCProcess extends Process {
	public String adptrMsgPtrnCd; 

	public java.lang.String adapterGroupName;

	public int logPssSeq;

	public int callCount;
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public java.util.Properties callProp;

	public EAIMessage resEaiMsg;

	public com.eactive.eai.common.message.EAIMessage reqEaiMsg;

	static Logger esbLogger = Logger.getLogger(Logger.LOGGER_ESBFW);
	private int svrLogLevel;
	private static ThreadLocal local = new ThreadLocal();

	static final long serialVersionUID = 1L;

	String guidLogPrefix = "";

	public EAIMessage clientReturn() {
		if (svrLogLevel >= 1) {
			try {
				long msgSndTm = System.currentTimeMillis();

				Long threadData = (Long) local.get();
				long processTm = msgSndTm - threadData.longValue();
				if (esbLogger.isInfo())
					esbLogger.info(
							guidLogPrefix + "  End... - 경과시간 : " + processTm + "(ms) - EAI Server Log Level is INFO");
			} catch (Exception e) {
				logger.warn("clientReturn", e);
			}
		}
		return resEaiMsg;
	}

	public void callService(com.eactive.eai.common.message.EAIMessage reqEaiMsg, java.util.Properties callProp) {
		this.reqEaiMsg = reqEaiMsg;
		this.callProp = callProp;
		if (this.reqEaiMsg == null)
			return;

		svrLogLevel = this.reqEaiMsg.getSvrLogLvl();

//        guidLogPrefix =  guidLogPrefix + " GUID["+reqEaiMsg.getKbMsg().getKBHeader().getGuIdNo()+"]";
		guidLogPrefix = guidLogPrefix + " GUID[" + getGuid(reqEaiMsg) + "]";

		if (svrLogLevel >= 1) {
			try {
				long msgRcvTm = System.currentTimeMillis();
				local.set(new Long(msgRcvTm));
				if (esbLogger.isInfo())
					esbLogger.info(guidLogPrefix + "  started... - EAI Server Log Level is INFO");
			} catch (Exception e) {
				logger.warn("callService", e);
			}
		}

		try {
			flow();
		} catch (Exception e) {
			printExceptionMessage(e);
			if (isSourceAsync()) {
				logSenderCtrlSend();
				callExceptionHandler();
			}
			return;
		}
	}

	public void flow() throws Exception {
		// isRealCall
		if (!isRealCall()) {
			return;
		}
		// 초기화
		init();
		// Outbound 프로세스 호출
		ifRouterProcess();

		while (isNextServiceExist()) {
			// GUID설정
			setGUID();
			// ServiceMessage 설정
			setCurrentService();
			// Outbound 호출
			ifRouterProcessEach();
		}
	}

	public void ifRouterProcess() throws Exception {
		try {
			this.resEaiMsg = IFRouter.process(this.reqEaiMsg, this.callProp);
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIFBF001";
			String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + " " + rspErrorMsg);
//			this.resEaiMsg.setRspErrCd(rspErrorCode);
//			this.resEaiMsg.setRspErrMsg(rspErrorMsg);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new Exception(rspErrorCode);
		}

		this.callCount++;
		// ----------------------------------------------------
		// 기동시스템이 Async 거래의 OUtbound에서 오류가 발생할 경우
		// ExceptionHandler를 통해 응답메시지를 전송한다.
		// ----------------------------------------------------
		if (EAIMessageKeys.ASYNC_SVC.equals(this.reqEaiMsg.getSvcTsmtUsgTp())) {
			if (!MessageUtil.checkRspErrCd(this.resEaiMsg.getRspErrCd())) {
				try {
//                    AdapterManager adapterManager = AdapterManager.getInstance();
//                    AdapterGroupVO inAdptGrpVO = adapterManager.getAdapterGroupVO(this.reqEaiMsg.getSngSysItfTp());
//                    String inAdapterMsgType = inAdptGrpVO.getMessageType();
////                    Object[] bizObjs  = this.reqEaiMsg.getBizMsg();
//                    Object[] bizObjs  = this.reqEaiMsg.getExtMsg().getBizData();
//                    if(EAITable.EBCDIC_TYPE.equals(inAdapterMsgType)) {                                        
//                        if(bizObjs != null && bizObjs[0] instanceof byte[]) {
//                            bizObjs[0] = CodeConversion.meToMixedAsc((byte[])bizObjs[0]);
//                        }                        
//                    }
////                    this.resEaiMsg.setBizMsg(bizObjs);
//                    this.resEaiMsg.getExtMsg().setBizData(bizObjs);
					
					String bizData = this.reqEaiMsg.getStandardMessage().getBizData();
					String inboundCharset = callProp.getProperty(com.eactive.eai.adapter.Keys.CHARSET_KEY_IN);
					this.resEaiMsg.getStandardMessage().setBizData(bizData, inboundCharset);

					ExceptionHandler.handle(this.resEaiMsg);
					// ----------------------------------------------------------

				} catch (Exception e) {
					if (logger.isError())
						logger.error(guidLogPrefix + " ExceptionHandler Call Error :" + e.getMessage());
				}
			}
		}
	}

	public void ifRouterProcessEach() throws Exception {
		try {
			this.resEaiMsg = IFRouter.process(this.reqEaiMsg, this.callProp);
		} catch (Exception e) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIFBF100";
			String orgErrorCode = ExceptionUtil.getErrorCode(e, rspErrorCode);
			String rspErrorMsg = ExceptionUtil.make(rspErrorCode, orgErrorCode, msgArgs);
			if (logger.isError())
				logger.error(guidLogPrefix + " " + rspErrorMsg);
//			this.resEaiMsg.setRspErrCd(rspErrorCode);
//			this.resEaiMsg.setRspErrMsg(rspErrorMsg);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			// throw new RuntimeException(rspErrorCode);
		}
		this.callCount++;
	}

	public void logSenderCtrlSend() {
//        String telgmDmndDstcd = extmessage.getSendRecv();
		String returnType = getReturnType(reqEaiMsg);

		if (STDMessageKeys.SEND_RECV_CD_RECV.equals(returnType)) {
			this.logPssSeq = 400;
		} else {
			this.logPssSeq = 200;
		}

		try {
			LogSender.send(this.logPssSeq, this.resEaiMsg, null);
		} catch (Exception e) {
			if (logger.isError())
				logger.error(guidLogPrefix + " AA Exception Logging Error :" + e.getMessage());
		}
	}

	public boolean checkServiceMsgSize() {
		// Outbound Error일 경우
		if (MessageUtil.checkRspErrCd(this.resEaiMsg.getRspErrCd()) && reqEaiMsg.getSvcMsgs().size() > 1) {
			return true;
		} else {
			return false;
		}
	}

	public boolean isOutboundCall() {
		return true;
	}

	public void init() throws Exception {
		InterfaceMapper mapper = this.reqEaiMsg.getMapper();
		StandardMessage standardMessage = this.reqEaiMsg.getStandardMessage();
		String guid = mapper.getGuid(standardMessage);
		String guidseq = mapper.getGuidSeq(standardMessage);

		if (logger.isDebug())
			logger.debug(guidLogPrefix + " REQ Current GUID [" + guid + "][" + guidseq + "]");
		mapper.nextGuidSeq(standardMessage);
		guidseq = mapper.getGuidSeq(standardMessage);
		if (logger.isDebug())
			logger.debug(guidLogPrefix + " REQ ADD PATHSEQ GUID [" + guid + "][" + guidseq + "]");

		if (logger.isDebug())
			logger.debug(guidLogPrefix + " set PROCESS_TYPE [" + EAIMessageKeys.PUBLISH_PROCESS + "]");
		this.reqEaiMsg.setSvcPssTp(EAIMessageKeys.PUBLISH_PROCESS);
		this.callCount = 0;
		this.reqEaiMsg.setSvcPssSeq(1);

		this.resEaiMsg = this.reqEaiMsg;
		this.adapterGroupName = reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp();
		
		AdapterManager adapterManager = AdapterManager.getInstance();
		AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(this.adapterGroupName);

		// 등록된 어댑터가 실제 존재하지 않는 경우 : 2009.04.03
		if (adptGrpVO == null) {
			String[] msgArgs = new String[1];
			msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
			String rspErrorCode = "RECEAIFBF001";
			String rspErrorMsg = ExceptionUtil.make(rspErrorCode, msgArgs) + "(Adapter Not Found - "
					+ this.adapterGroupName + ")";
			if (logger.isError())
				logger.error(guidLogPrefix + " " + rspErrorMsg);
//			this.resEaiMsg.setRspErrCd(rspErrorCode);
//			this.resEaiMsg.setRspErrMsg(rspErrorMsg);
			this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
			throw new Exception(rspErrorCode);
		}

		this.adptrMsgPtrnCd = adptGrpVO.getAdptrMsgPtrnCd();

		// 2009.03.11
		// AA가 아니고 기동이 KB표준이 아닌 경우
		// Adapter의 timeout값을 설정한다.
		try {
			String svcTsmtUsgTp = this.reqEaiMsg.getSvcTsmtUsgTp(); // 기동 호출방식
			String psvItfTp = this.reqEaiMsg.getCurrentSvcMsg().getPsvItfTp(); // 수동 호출방식
			if (!(EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp))
					&& !(com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.reqEaiMsg.getStdMsgUsgCls()))) {
				// SA 또는 SNA Adapter일 경우에 는 SA Timeout값을 설정
				if ((EAIMessageKeys.SYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp))
						|| Keys.TYPE_SNA.equals(adptGrpVO.getType())) {
					int saTimeoutSec = this.reqEaiMsg.getCurrentSvcMsg().getTmoVl();
					if (logger.isDebug())
						logger.debug(guidLogPrefix + " SA TimeoutValue [" + saTimeoutSec + "]");
					setTimeout(this.reqEaiMsg, "" + saTimeoutSec);
				} else {
					int timeout = ServiceUtil.getTimeoutValue(adapterGroupName);
					if (logger.isDebug())
						logger.debug(guidLogPrefix + " Target Adapter TimeoutValue [" + timeout + "]");
					if (timeout > 0) {
						if (logger.isDebug())
							logger.debug(guidLogPrefix + " Set Adapter TimeoutValue [" + timeout + "] to KBMessage");
						setTimeout(this.reqEaiMsg, "" + timeout);
					}
				}
			}
		} catch (Exception e) {
			if (logger.isWarn()) {
				logger.warn(guidLogPrefix + " Get Adapter TimeoutValue Error - ", e);
			}
		}
	}

	public void printExceptionMessage(Exception e) {
		// Exception e = this.context.getExceptionInfo().getException();
		if (logger.isError())
			logger.error(guidLogPrefix + " ExceptionPath : " + e.getMessage());
	}

	public boolean isSourceAsync() {
		if (EAIMessageKeys.ASYNC_SVC.equals(this.reqEaiMsg.getSvcTsmtUsgTp())) {
			return true;
		} else {
			return false;
		}
	}

	public void callExceptionHandler() {
		try {
			AdapterManager adapterManager = AdapterManager.getInstance();
			AdapterGroupVO inAdptGrpVO = adapterManager.getAdapterGroupVO(this.reqEaiMsg.getSngSysItfTp());
			String inAdapterMsgType = inAdptGrpVO.getMessageType();
			if (EAITable.EBCDIC_TYPE.equals(inAdapterMsgType)) {
				String bizData = this.reqEaiMsg.getStandardMessage().getBizData();
				byte[] asc = CodeConversion.meToMixedAsc(bizData.getBytes());
				try {
					String inboundCharset = callProp.getProperty(com.eactive.eai.adapter.Keys.CHARSET_KEY_IN);
					this.reqEaiMsg.getStandardMessage().setBizData(new String(asc), inboundCharset);
				} catch (Exception e) {
					logger.error("setBizData error", e);
				}
			}
			ExceptionHandler.handle(this.reqEaiMsg);
		} catch (Exception e) {
			if (logger.isError())
				logger.error(guidLogPrefix + " ExceptionHandler Call Error :" + e.getMessage());
		}
	}

	public boolean isRealCall() {
		if (this.callProp != null) {
			String mode = this.callProp.getProperty(EAIKeys.CALL_MODE_KEY);
			if (mode != null && EAIKeys.CALL_MODE_WARMUP.equals(mode)) {
				logger.warn(guidLogPrefix + " Warming Up Called");
				return false;
			} else {
				return true;
			}
		} else {
			return true;
		}
	}

	public boolean isNextServiceExist() {
		if ((reqEaiMsg.getSvcMsgs().size() > 1) && (reqEaiMsg.getSvcMsgs().size() > this.callCount)) {
			return true;
		} else {
			return false;
		}
	}

	private String getAdapterType(String adapterGroupName) {
		AdapterManager adapterManager = AdapterManager.getInstance();
		AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(this.adapterGroupName);
		return adptGrpVO.getType();
	}

	private boolean isNKESA(String adapterGroupName) {
		AdapterManager adapterManager = AdapterManager.getInstance();
		AdapterPropManager manager = AdapterPropManager.getInstance();

		AdapterGroupVO adptGrpVO = null;
		AdapterVO adptVO = null;

		adptGrpVO = adapterManager.getAdapterGroupVO(adapterGroupName);
		if (adptGrpVO == null || !Keys.TYPE_HTTP.equals(adptGrpVO.getType()))
			return false;
		
		Iterator<AdapterVO> adapters = adptGrpVO.getAdapters();
		if(adapters != null && adapters.hasNext()) {
			adptVO = adptGrpVO.getAdapters().next();
		}
		if (adptVO == null)  return false;
		
		Properties httpProp = (Properties) manager.getProperties(adptVO.getPropGroupName()).clone();
		String method = httpProp.getProperty(HttpClientAdapterServiceKey.METHOD);
		if ("NKESA".equals(method)) return true;
		else return false;
	}

	public void setGUID() throws Exception {
		InterfaceMapper mapper = this.resEaiMsg.getMapper();
		StandardMessage standardMessage = this.resEaiMsg.getStandardMessage();
		String guid = mapper.getGuid(standardMessage);
		String guidseq = mapper.getGuidSeq(standardMessage);

		if (logger.isDebug())
			logger.debug(guidLogPrefix + " REQ Current GUID [" + guid + "][" + guidseq + "]");
		mapper.nextGuidSeq(standardMessage);
		guidseq = mapper.getGuidSeq(standardMessage);
		if (logger.isDebug())
			logger.debug(guidLogPrefix + " REQ ADD PATHSEQ GUID [" + guid + "][" + guidseq + "]");

		String svcTsmtUsgTp = this.reqEaiMsg.getSvcTsmtUsgTp(); // 기동 호출방식
		String psvItfTp = this.reqEaiMsg.getCurrentSvcMsg().getPsvItfTp(); // 수동 호출방식

		if ((!(com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd))
				&& !(EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp)))
				|| ((com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd))
						&& (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp)
								&& EAIMessageKeys.SYNC_SVC.equals(psvItfTp)))) {
			String prcssRtdTranCd = mapper.getReturnServiceId(standardMessage);

			if (prcssRtdTranCd != null && prcssRtdTranCd.length() >= 14) {
				String cicsTrncd = prcssRtdTranCd.substring(0, 4);
				String telgmRecvTranCd = prcssRtdTranCd.substring(4, 14);
				mapper.setServiceId(standardMessage, telgmRecvTranCd);
			} else {
				if (logger.isInfo()) {
					logger.info(guidLogPrefix + "- PrcssRtdTranCd Length < 14 [" + prcssRtdTranCd + "]");
				}
			}
		}

		if (!(EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTp) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp))
				&& (com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.reqEaiMsg.getStdMsgUsgCls()))
				&& (STDMessageKeys.RECOVER_YN_YES.equals(getRecoverYn(this.reqEaiMsg)) ) ) {
			String reqOgtranGuIdNo = getOrgGuid(this.reqEaiMsg);
			mapper.setOrgGuid(standardMessage, reqOgtranGuIdNo);
			if (logger.isInfo()) {
				logger.info(guidLogPrefix + " OgtranGuIdNo 복원 " + this.reqEaiMsg.getSvcOgNo() + " OgtranGuIdNo ["
						+ mapper.getOrgGuid(standardMessage) + "]");
			}
		}
	}

	public void setCurrentService() throws Exception {
		if (logger.isDebug())
			logger.debug(guidLogPrefix + " Outound Service Call - ");
		String keyMgtMsgVl = reqEaiMsg.getCurrentSvcMsg().getKeyMgtMsgVl();
		if (logger.isDebug())
			logger.debug(guidLogPrefix + " keyMgtMsgVl[" + keyMgtMsgVl + "]");
		reqEaiMsg.setSvcPssSeq(reqEaiMsg.getSvcPssSeq() + 1);
		reqEaiMsg.getCurrentSvcMsg().setKeyMgtMsgVl(keyMgtMsgVl);
	}
}
