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.filter.HttpAdapterFilter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonToSetStatusFilter 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);

        int httpStatus = 200;

        if (rootNode.has("apiRsltCd") && !rootNode.get("apiRsltCd").asText().isEmpty()) {
            try {
                String statusParam = rootNode.get("apiRsltCd").asText();
                httpStatus = Integer.parseInt(statusParam);
            } catch (NumberFormatException e) {
                httpStatus = 400; // 잘못된 입력일 경우 400 Bad Request 반환
            }
            // HTTP 상태 코드 설정
            response.setStatus(httpStatus);
        }
        return message;
    }

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

        if (rootNode.has("apiRsltCd") && !rootNode.get("apiRsltCd").asText().isEmpty()) {
            try {
                String statusParam = rootNode.get("apiRsltCd").asText();
                httpStatus = Integer.parseInt(statusParam);
            } catch (NumberFormatException e) {
                httpStatus = 400; // 잘못된 입력일 경우 400 Bad Request 반환
            }
            // HTTP 상태 코드 설정
            response.setStatus(httpStatus);
        }
        return resultMessage;
    }

    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);
    }
}
