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

import java.util.Properties;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.handler.AdapterErrorMessageHandler;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.message.StandardMessage;
import com.eactive.eai.message.manager.StandardMessageManager;
import com.eactive.eai.message.service.InterfaceMapper;
import com.ext.eai.common.stdmessage.STDMessageKeys;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class LonErrorMsgHandler implements AdapterErrorMessageHandler {

	@Override
	public Object generateNonStandardErrorResponseMessage(String inboudnAdapterGroupName, String inboudnAdapterName,
			Properties callProp, Object outboundRequestData, StandardMessage resStandardMessage) throws Exception{
		
		if(resStandardMessage != null && isErrorMessage(resStandardMessage)) {
			AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(inboudnAdapterGroupName);
			if(MessageType.JSON.equals(adapterGroupVO.getMessageType())) {
				ObjectMapper objectMapper = new ObjectMapper();
				String requestMessage = (String) outboundRequestData;
				JsonNode requestJson = objectMapper.readTree(requestMessage);
				String alncInstCd = requestJson.get("dataCmn").get("alncInstCd").asText();
				
				ObjectNode responseJson = objectMapper.createObjectNode();
				ObjectNode dataCmnNode = objectMapper.createObjectNode();
				responseJson.set("dataCmn", dataCmnNode);
				dataCmnNode.put("fnclInstCd", "KBK");
				dataCmnNode.put("alncInstCd", alncInstCd);
				dataCmnNode.put("tlgrRspnsCd", "0210");
				
				return responseJson.toString();
			}
		}
		
		
		return "";
	}
	
	private boolean isErrorMessage(StandardMessage standardMessage) {
		InterfaceMapper mapper = StandardMessageManager.getInstance().getMapper();
		String responseType = mapper.getResponseType(standardMessage);
		return STDMessageKeys.RESPONSE_TYPE_CODE_E.equals(responseType);
	}

}
