package com.eactive.eai.common.inflow;

import java.lang.reflect.Method;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.Logger;

public class InflowControlUtil {
	private InflowControlUtil() {
	}

	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Bucket getBucket() {
		Properties inFlowProp = PropManager.getInstance().getProperties("INFLOW");
		String className = inFlowProp.getProperty("inflow.control.bucket.className");
		if (StringUtils.isBlank(className)
				|| StringUtils.equals(className, "com.eactive.eai.common.inflow.InflowControlManager")) {
			return InflowControlManager.getBucket();
		} else {
			try {
				Class clazz = Class.forName(className);
				Method method = clazz.getMethod("getBucket", (Class<?>[]) null);
				return (Bucket) method.invoke(null, (Object[]) null);
			} catch (Exception e) {
				logger.error("Method call error class= {}, method= getBucket", className);
				logger.error(e.getMessage());
			}
		}

		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean isTargetOfInflowControl(EAIServerManager eaiServerManager, EAIMessage eaiMessage) {
		Properties inFlowProp = PropManager.getInstance().getProperties("INFLOW");
		String controlInflow = inFlowProp.getProperty("inflow.control.yn", "N");

		if (!"Y".equalsIgnoreCase(controlInflow)) {
			return false;
		}

		String className = inFlowProp.getProperty("inflow.control.bucket.className");
		if (StringUtils.isBlank(className)
				|| StringUtils.equals(className, "com.eactive.eai.common.inflow.InflowControlManager")) {
			return InflowControlManager.isTargetOfInflowControl(eaiServerManager, eaiMessage).booleanValue();
		} else {
			try {
				Class clazz = Class.forName(className);
				Method method = clazz.getMethod("isTargetOfInflowControl", EAIServerManager.class, EAIMessage.class);
				Boolean returnBoolean = (Boolean) method.invoke(null, eaiServerManager, eaiMessage);
				return returnBoolean.booleanValue();
			} catch (Exception e) {
				logger.error("Method call error class= {}, method= isTargetOfInflowControl", className);
				logger.error(e.getMessage());
			}
		}

		return false;
	}
}
