package com.eactive.eai.custom.kjb.adapter.http.client.filter;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.eactive.eai.common.util.Logger;

public abstract class HttpClientAdapterBaseFilter implements HttpClientAdapterFilter {
	protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
	protected String filterName = "";
	protected List<HttpClientAdapterFilter> filters;
	
	protected HttpClientAdapterBaseFilter(String filterName) {
		this.filterName = filterName;
		filters = new ArrayList<>();
		logger.info("{}] filter created.", filterName);
	}
	
	protected void addFilter(HttpClientAdapterFilter filter) {
		filters.add(filter);
		logger.info("{}] sub filter({}) added. filters= {}", filterName, filter, filters);
	}

	@Override
	public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
			throws Exception {
		try {
			Object filteredMessage = message;
			for(HttpClientAdapterFilter subFilter : filters) {
				logger.debug("{}] sub filter({}) doPreFilter start.", filterName, subFilter);
				filteredMessage = subFilter.doPreFilter(adptGrpName, adptName, prop, filteredMessage, tempProp);
				logger.debug("{}] sub filter({}) doPreFilter end.", filterName, subFilter);
			}
			
			return filteredMessage;
		} catch (Exception e) {
			logger.error(this.filterName + "] doPreFilter error.", e);
			throw e;
		}
	}

	@Override
	public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
			Properties tempProp) throws Exception {
		try {
			Object filteredMessage = message;
			for(HttpClientAdapterFilter subFilter : filters) {
				logger.debug("{}] sub filter({}) doPostFilter start.", filterName, subFilter);
				filteredMessage = subFilter.doPostFilter(adptGrpName, adptName, prop, filteredMessage, tempProp);
				logger.debug("{}] sub filter({}) doPostFilter end.", filterName, subFilter);
			}
			return filteredMessage; 
		} catch (Exception e) {
			logger.error(this.filterName + "] doPostFilter error.", e);
			throw e;
		}
	}
	
	

}
