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

import java.util.Properties;

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

import org.springframework.http.HttpStatus;

import com.eactive.eai.adapter.http.dynamic.filter.FilterCryptoException;
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
import com.eactive.eai.adapter.service.DJBApiAdapterService;
import com.eactive.eai.common.util.JacksonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * InCryptoFilter를 멤버변수로 관리하는 HttpAdapterFilter 구현체.
 *
 * 멤버변수에 세팅된 값을 Properties로 변환하여 {@link InCryptoFilter}에 위임한다.
 * 값이 blank인 멤버변수는 Properties에 포함하지 않으며, InCryptoFilter의 기본값이 적용된다.
 */
public class EncFieldInCryptoFilter implements HttpAdapterFilter {

    private final InCryptoFilter filter = new InCryptoFilter();

    @Override
    public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        return filter.doPreFilter(adptGrpName, adptName, message, setProp(prop), request, response);
    }

    @Override
    public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
    	try {
    		JsonNode root = JacksonUtil.readTree(resultMessage);
			ObjectNode rootObjectNode = (ObjectNode) root;
			String headerGroupName = prop.getProperty(DJBApiAdapterService.HEADER_GROUP);
			JsonNode header = null;
			if(headerGroupName != null) {
				header = rootObjectNode.get(headerGroupName);
				rootObjectNode.remove(headerGroupName);
			}
			
			Object enc = filter.doPostFilter(adptGrpName, adptName, rootObjectNode, setProp(prop), request, response);
			ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
			if(header != null)
				encJson.set(headerGroupName, header);
			
			return encJson;
			
		} catch (Exception e) {
			throw new FilterCryptoException("암호화 오류", InCryptoFilter.ERROR_ENC_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
		}
    }

    protected Properties setProp(Properties p) {
    	p.setProperty(InCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
    	p.setProperty(InCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
        return p;
    }

    
}
