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

import java.io.UnsupportedEncodingException;
import java.util.Properties;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JsonToStdConverterFilter implements HttpAdapterFilter {
    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
                              HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonNode rootNode = parseJson(adptGrpName, message);

        if (rootNode.has("header_part")) {
            JsonNode headerPart = rootNode.path("header_part");
            if (!headerPart.has("eaiIntfId") || headerPart.get("eaiIntfId").asText().isEmpty()) {
                // /api/v1/public/getUserInfo.svc
                String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
                String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH) + "/";

                // getUserInfo.svc
                String eaiIntfId = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);

                // header_part 아래 eaiIntfId가 추가 또는 수정
                if (headerPart instanceof ObjectNode) {
                    ((ObjectNode) headerPart).put("eaiIntfId", eaiIntfId);
                    // 요청 응답 구분코드 강제 설정 -> API명 찾아갈때 필요
                    if (!headerPart.has("reqRspnsDscd")) {
                        ((ObjectNode) headerPart).put("reqRspnsDscd", "S");
                    }

                    // GUID 강제 설정
                    String orgnlTx = "";
                    if (headerPart.has("orgnlTx") &&  !headerPart.get("orgnlTx").asText().isEmpty()) {
                        orgnlTx = headerPart.get("orgnlTx").asText();
                    }
                    if (!headerPart.has("tlgrWrtnDt")) {
                        ((ObjectNode) headerPart).put("tlgrWrtnDt", orgnlTx);
                    }
                    if (!headerPart.has("tlgrCrtnSysNm")) {
                        ((ObjectNode) headerPart).put("tlgrCrtnSysNm", "");
                    }
                    if (!headerPart.has("tlgrSrlNo")) {
                        ((ObjectNode) headerPart).put("tlgrSrlNo", "");
                    }
                }
            }
        }
        else {
            return message;
        }
        return rootNode.toString();
    }

    @Override
    public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
                               HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonNode rootNode = parseJson(adptGrpName, resultMessage);

        if (rootNode.has("header_part")) {
            JsonNode headerPart = rootNode.path("header_part");
            if (!headerPart.has("eaiIntfId") || headerPart.get("eaiIntfId").asText().isEmpty()) {
                // /api/v1/public/getUserInfo.svc
                String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
                String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH) + "/";

                // getUserInfo.svc
                String eaiIntfId = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);

                // header_part 아래 eaiIntfId가 추가 또는 수정
                if (headerPart instanceof ObjectNode) {
                    ((ObjectNode) headerPart).put("eaiIntfId", eaiIntfId);
                    // 요청 응답 구분코드 강제 설정 -> API명 찾아갈때 필요
                    ((ObjectNode) headerPart).put("reqRspnsDscd", "S");
                }
            }
        }
        else {
            return resultMessage;
        }
        return rootNode.toString();
    }

    public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
            String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
        String orgMessageString;
        if(message instanceof byte[]) {
            orgMessageString = new String((byte[])message, charset);
        } else {
            orgMessageString = (String) message;
        }

        return mapper.readTree(orgMessageString);
    }

}
