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

import java.util.concurrent.ConcurrentHashMap;

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

public class HttpAdapterFilterFactory {
	static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
	static String basePackage = "com.eactive.eai.adapter.http.dynamic.filter";
	static String customBasePackage = "com.eactive.eai.custom.adapter.http.dynamic.filter";
	static private ConcurrentHashMap<String, HttpAdapterFilter> h = new ConcurrentHashMap<String, HttpAdapterFilter>();

	public static HttpAdapterFilter createFilter(String type) {
		if (h.containsKey(type)) {
			return (HttpAdapterFilter) h.get(type);
		}

		HttpAdapterFilter filter = null;
		switch (HttpAdapterFilterType.getValue(type)) {
		case APIAUTHFILTER:
			filter = new ApiAuthFilter();
			break;
		case JWTAUTHFILTER:
			filter = new JwtAuthFilter();
			break;
		case IPWHITELISTFILTER:
			filter = new IpWhiteListFilter();
			break;
		case ADAPTERALLOWIPLISTFILTER:
			filter = new AdapterAllowIPListFilter();
			break;
		case HMAC_SHA256:
			filter = new HmacSha256VerifyFilterKjb();
			break;
		case REFLECTALLHEADER:
			filter = new ReflectAllHeaderFilter();
			break;
		default:
			filter = classForName(type);
			if (filter == null) {
				filter = classForName(basePackage + "." + type);
			}
			if (filter == null) {
				filter = classForName(customBasePackage + "." + type);
			}
			break;
		}

		if (filter != null) {
			h.put(type, filter);
			return filter;
		} else {
			return null;
		}
	}

	private static HttpAdapterFilter classForName(String type) {
		try {
			Class<?> cl = Class.forName(type);
			return (HttpAdapterFilter) cl.newInstance();
		} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
			logger.error("Cannot create a HttpAdapterFilter. - {}", type);
			return null;
		}
	}
}
