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

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

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

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.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class KbankEaiJsonParseFilter 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);
		
		ObjectNode replacedJson = mapper.createObjectNode();
		for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();) {
			String fieldName = it.next();
			String value = rootNode.get(fieldName).asText();
			JsonNode jsonNode = mapper.readTree(value);
			replacedJson.set(fieldName, jsonNode);
		}
		
		return replacedJson.toString();
	}

	@Override
	public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonNode rootNode = parseJson(adptGrpName, resultMessage);
		
		ObjectNode replacedJson = mapper.createObjectNode();
		for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();) {
			String fieldName = it.next();
			JsonNode childNode = rootNode.get(fieldName);
			String childString = mapper.writeValueAsString(childNode);
			replacedJson.put(fieldName, childString);
		}
		
		return replacedJson.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);
	}

}
