package com.eactive.eai.custom.adapter.handler;

import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.adapter.handler.TemplateAdapterErrorMsgHandler;
import com.eactive.eai.adapter.handler.TemplateCodeConvertAdapterErrorMsgHandler;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
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.InterfaceMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterErrorMsgHandler {

	private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);

	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

	@Override
	public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
			Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg) throws Exception {

		Object responseMsessage = super.generateNonStandardErrorResponseMessage(inboundAdapterGroupName,
				inboundAdapterName, callProp, outboundRequestData, resEaiMsg);

		logger.debug("generateNonStandardErrorResponseMessage - {}", responseMsessage);

		if (!(responseMsessage instanceof String)) {
			return responseMsessage;
		}

		String jsonStr = (String) responseMsessage;
		if (StringUtils.isBlank(jsonStr)) {
			return responseMsessage;
		}

		JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);

		boolean modified = false;

		if (modified) {
			responseMsessage = OBJECT_MAPPER.writeValueAsString(rootNode);
		}

		return responseMsessage;
	}
	
	/**
	 * 표준 -> 비표준 거래 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
	 */
	@Override
	public Object generateOutboundErrorResponseMessage(String outboundadapterGroupName, String outboundadapterName,
			Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg) throws Exception {

		String msgCd = "error";
		String msgCtnt = "IF오류";
		String msgDesc = "";
		// 에러에 대한 응답메시지
		if (callProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP) instanceof Map) {
			Map<String, Object> map = (Map<String, Object>) callProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP);
			Object responseBody = map.get(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE);

			if (responseBody instanceof String) {
				String jsonStr = (String) responseBody;
				if (!StringUtils.isBlank(jsonStr)) {
					JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
					StringBuffer sb = new StringBuffer();
					JsonNode errorCode = rootNode.get("error_code");
					if(errorCode != null)
						sb.append(errorCode.textValue());
					
					sb.append("/");
					JsonNode errorMessage = rootNode.get("error_message");
					if(errorMessage != null)
						sb.append(errorMessage.textValue());
					
					msgDesc = sb.toString();
					msgCd = "BFEX03216";
					msgCtnt = "참가기관코드 에러입니다.";
					logger.debug("오류 응답 수신 - {}", jsonStr);
				}
			}
		}

		StandardMessage standardMessage = resEaiMsg.getStandardMessage();
		// msg_dvcd = EM (에러메시지)
		standardMessage.setData(StandardMessageCoordinatorDJB.MSG_DVCD, "NM");

		// 출력속성코드 = 1(팝업)
		standardMessage.setData(StandardMessageCoordinatorDJB.MSG_OUTP_ATRB_CD, "");

		// MSG_LIST 1건 구성
		standardMessage.setData(StandardMessageCoordinatorDJB.MSG_LIST_ROWCNT, "0");
		StandardItem msgPart = standardMessage.findItem("MSG");
		msgPart.getChilds().remove("MSG_LIST");

		StandardMessageManager manager = StandardMessageManager.getInstance();
		InterfaceMapper mapper = manager.getMapper();

		// mapper 에러코드 설정
		mapper.setErrorCode(standardMessage, msgCd);
		mapper.setErrorMsg(standardMessage, msgCtnt);
		if (StringUtils.isNotEmpty(msgDesc))
			standardMessage.setData(StandardMessageCoordinatorDJB.MSG_OUTP_MSG_DESC, msgDesc);

		// 성공 처리 처럼 진행한다.
		resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);

		return null;

	}

}
