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

import java.util.Properties;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

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

public class AdapterBlockIpListFilter implements HttpAdapterFilter {
	static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);

	@Override
	public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		String requestIp = getClientIp(request);
		try {
			String blockIps = prop.getProperty("BLOCK_IP", "");
			if (StringUtils.isBlank(blockIps)) {
				return message;
			}

			if (IpUtil.isMatchIp(blockIps, requestIp)) {
				throw new FilterException("This IP was not allowed-" + requestIp, HttpStatus.FORBIDDEN.value());
			}
		} catch (FilterException e) {
			logger.debug(e.getMessage());
			throw e;
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new JwtAuthException(JwtAuthFilter.ERROR_AUTHORIZATION_FAIL, "Client IP check failed-" + requestIp);
		}

		return message;
	}

	private String getClientIp(HttpServletRequest request) {
		String ipAddress = request.getHeader("X-FORWARDED-FOR");
		if (ipAddress == null) {
			ipAddress = request.getRemoteAddr();
		}
		if (ipAddress.indexOf(",") >= 0) {
			ipAddress = org.springframework.util.StringUtils.tokenizeToStringArray(ipAddress, ",")[0];
		}
		return ipAddress;
	}

	@Override
	public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		return resultMessage;
	}
}
