package com.eactive.eai.custom.message;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.common.dao.Keys;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.inbound.processor.ProcessVO;
import com.eactive.eai.inbound.processor.Processor;
import com.eactive.eai.message.StandardItem;
import com.eactive.eai.message.StandardMessage;
import com.eactive.eai.message.manager.StandardMessageManager;
import com.eactive.eai.message.service.DefaultStandardMessageCoordinator;
import com.eactive.eai.message.service.InterfaceMapper;
import com.ext.eai.common.stdmessage.STDMessageKeys;
import org.apache.commons.lang.StringUtils;

import java.net.UnknownHostException;
import java.util.LinkedHashMap;
import java.util.Properties;

public class StandardMessageCoordinatorKJB extends DefaultStandardMessageCoordinator {
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private static final String MESSAGE_PART = "Message";
	private static final String MESSAGE_PART_HEADER_PART = "Message.Msg_Header";
	private static final String MESSAGE_PART_MSG_HEDR_KNCD = "Message.Msg_Header.MSG_HEDR_KNCD";
	private static final String MESSAGE_PART_MSG_HEDR_LEN = "Message.Msg_Header.MSG_HEDR_LEN";
	private static final String MESSAGE_PART_BODY_PART = "Message.Msg_Body";
	private static final String MESSAGE_PART_OUTPUT_MSG_CD = "Message.Msg_Body.OUTPUT_MSG_CD";
	private static final String MESSAGE_PART_OUTPUT_MSG_CTNT = "Message.Msg_Body.OUTPUT_MSG_CTNT";
	private static final String MESSAGE_PART_OUTPUT_MSG_GRID = "Message.Msg_Body.Output_Msg_Grid";
	private static final String COMMON_PART_GROUP_CMD_CD = "Common.Service_info.GROUP_CMP_CD";
	private static final String COMMON_PART_OTSD_CHNL_INST_CD = "Common.Service_info.OTSD_CHNL_INST_CD";
	private static final String DATA_HEADER_DATA_HEDR_LEN = "Data_Part.Data_Header.DATA_HEDR_LEN";

	@Override
	public void coordinateAfterParsing(StandardMessage standardMessage, Object paramObject, Properties prop) {
	}

	@Override
	public void coordinateBeforeStandardMessageSend(StandardMessage standardMessage, String msgType, String charset) {
		makeupDataHeaderLength(standardMessage, charset);
	}

	@Override
	public void coordinateBeforeResponse(StandardMessage standardMessage, ProcessVO processVO, Properties prop, String charset) {
		makeupDataHeaderLength(standardMessage, charset);
	}

	@Override
	public void coordinateAfterCreateMessageByRule(StandardMessage standardMessage, Object paramObject, Properties prop) {
		// guid 설정
		StandardMessageManager standardManager = StandardMessageManager.getInstance();
		InterfaceMapper mapper = standardManager.getMapper();

		//GUID 설정
		String groupCmdCd = standardMessage.findItemValue(COMMON_PART_GROUP_CMD_CD);

		String guid = GUIDGeneratorKJB.getGUID(groupCmdCd);

		mapper.setGuid(standardMessage, guid);

		StandardItem dataHeaderEtc = standardMessage.findItem("Data_Part.Data_Header_Etc");
		dataHeaderEtc.setHidden(true);

		//기관코드, 텔러번호 설정
		//Adapter에 셋팅된 기관코드를 셋팅한다.
		String adapterGroupName  = prop.getProperty(Processor.ADAPTER_GROUP_NAME);
		AdapterManager adapterManager = AdapterManager.getInstance();
		AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(adapterGroupName);

		// Adapter의 기관코드를 얻어온다.
		//TODO: 기관코드의 경우 현재 EAPIM 시스템에 컬럼은 있으나 설정을 사용하지 않고있으므로 불필요 할 경우 사용하지 않는다, 필요 할 경우 추가한다.
		String inAdapterOsidInstiNo = adptGrpVO.getOsidInstiNo();
		if(inAdapterOsidInstiNo != null && inAdapterOsidInstiNo.trim().length() > 0) {
			standardMessage.setData(COMMON_PART_OTSD_CHNL_INST_CD, inAdapterOsidInstiNo);
			if (logger.isDebug()) {
				logger.debug("FIELD SET " + COMMON_PART_OTSD_CHNL_INST_CD + " << "+inAdapterOsidInstiNo);
			}
		}

		//2012-12-17 나영채 차장 타발요청에만 셋팅해달라고 요청
		//전문요청일자
		standardMessage.setData("Common.BizProc_Info.MESG_DMAN_DT", DatetimeUtil.getCurrentDate());
		//전문요청시간
		standardMessage.setData("Common.BizProc_Info.MESG_DMAN_TKTM", DatetimeUtil.getFormattedDate("HHmmssSSS"));


		//2012-07-24 임의 로 영업일자에 system시간 설정
		standardMessage.setData("Common.BizProc_Info.BZOP_DT", DatetimeUtil.getCurrentDate());

		EAIServerManager eaiServerManager = EAIServerManager.getInstance();
		//비표준일경우 시스템 운영환경 구분코드를 셋팅한다.
		standardMessage.setData("Common.Service_info.SYS_OPRT_ENV_DVCD", getSysOprtEnvDvcd(eaiServerManager));

		//헤더부 최초전송IP주소	FRST_TRNM_IPAD
        try {
			standardMessage.setData("Header.Src_System.FRST_TRNM_IPAD", java.net.InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
        }
    }
	
	@Override
	public boolean coordinateSetStandardMessageError(StandardMessage standardMessage, InterfaceMapper mapper,
			String errCode, String errMsg) {
		
		mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_E);
		mapper.setSendRecvDivision(standardMessage, STDMessageKeys.SEND_RECV_CD_RECV);

		StandardItem messagePart = standardMessage.findItem(MESSAGE_PART);
		messagePart.setHidden(false);
		messagePart.setSize(1);

		StandardItem messageHeaderPart = standardMessage.findItem(MESSAGE_PART_HEADER_PART);
		messageHeaderPart.setSize(1);
		StandardItem messageBodyPart = standardMessage.findItem(MESSAGE_PART_BODY_PART);
		messageBodyPart.setSize(1);

		errCode = StringUtils.defaultString(errCode);
		String siteErrCode = MessageUtil.getTobeCode(errCode);
		String siteErrMessage;
		switch(errCode) {
			case("RECEAIIRP070"):
				siteErrMessage = "거래 통제 되었습니다.";
				break;
			default:
				siteErrMessage = MessageUtil.getTobeMessage(errCode);
				break;
		}

		mapper.setErrorCode(standardMessage, siteErrCode);

		standardMessage.setData(MESSAGE_PART_MSG_HEDR_KNCD, "EM");
		standardMessage.setData(MESSAGE_PART_OUTPUT_MSG_CD, siteErrCode);
		StandardItem msgGrid = standardMessage.findItem(MESSAGE_PART_OUTPUT_MSG_GRID);
		LinkedHashMap<String, StandardItem> msgGridFirstChilds = msgGrid.getArrayChilds(0, true);
		msgGridFirstChilds.get("OUTPUT_MSG_CD").setValue(siteErrCode);
		msgGridFirstChilds.get("OUTPUT_MSG_CTNT").setValue(siteErrMessage);
		//Message.Msg_Body.OUTPUT_MSG_CTNT
		mapper.setErrorMsg(standardMessage, siteErrMessage);
		int len = standardMessage.getBytesDataLengthForPath(MESSAGE_PART_BODY_PART);
		String lenStr = StringUtils.leftPad(String.valueOf(len), 8, '0');
		standardMessage.setData(MESSAGE_PART_MSG_HEDR_LEN, lenStr);

		return false;
	}

	
	@Override
	public void coordinateAfterRecvNonStdSyncResponse(StandardMessage responseMessage) {
		StandardItem messagePart = responseMessage.findItem(MESSAGE_PART);
		messagePart.setHidden(false);
		messagePart.setSize(1);

		StandardItem messageHeaderPart = responseMessage.findItem(MESSAGE_PART_HEADER_PART);
		messageHeaderPart.setSize(1);
		StandardItem messageBodyPart = responseMessage.findItem(MESSAGE_PART_BODY_PART);
		messageBodyPart.setSize(1);

		responseMessage.setData(MESSAGE_PART_MSG_HEDR_KNCD, "NM");
		responseMessage.setData(MESSAGE_PART_OUTPUT_MSG_CD, "100000    ");
		responseMessage.setData(MESSAGE_PART_OUTPUT_MSG_CTNT, "정상처리");
		StandardItem msgGrid = responseMessage.findItem(MESSAGE_PART_OUTPUT_MSG_GRID);
		LinkedHashMap<String, StandardItem> msgGridFirstChilds = msgGrid.getArrayChilds(0, true);
		msgGridFirstChilds.get("OUTPUT_MSG_CD").setValue("100000    ");
		msgGridFirstChilds.get("OUTPUT_MSG_CTNT").setValue("정상처리");
		int len = responseMessage.getBytesDataLengthForPath(MESSAGE_PART_BODY_PART);
		String lenStr = StringUtils.leftPad(String.valueOf(len), 8, '0');
		responseMessage.setData(MESSAGE_PART_MSG_HEDR_LEN, lenStr);
	}

	public String getSysOprtEnvDvcd(EAIServerManager eaiServerManager) {
		String result = "";
		if (eaiServerManager.isPEAIServer()){ //운영
			result = STDMessageKeys.SYS_OPRT_ENV_DVCD_ONLINE;
		}else if (eaiServerManager.isDEAIServer()){ //개발
			result = STDMessageKeys.SYS_OPRT_ENV_DVCD_DEV;
		}else if (eaiServerManager.isSEAIServer()){ //테스트/검증
			result = STDMessageKeys.SYS_OPRT_ENV_DVCD_TESTSTAGE;
		}
		return result;
	}

	private static void makeupDataHeaderLength(StandardMessage standardMessage, String charset) {
		String dataBytesLengthStr = null;
		try {
			dataBytesLengthStr = String.valueOf(standardMessage.getBizDataBytes(charset).length);
			String dataHeaderLength = StringUtils.leftPad(dataBytesLengthStr, 8, '0');
			standardMessage.setData(DATA_HEADER_DATA_HEDR_LEN, dataHeaderLength);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
