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.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.util.IpUtil;

public class AdapterAllowIPListFilter 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 allowedIps = prop.getProperty(HttpAdapterServiceKey.ALLOW_IP, "");
			if (StringUtils.isBlank(allowedIps)) {
				return message;
			}

			if (!IpUtil.isMatchIp(allowedIps, 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;
	}

	private String assignClientId(Properties prop, HttpServletRequest request) {
		String clientId = null;
		try {
			// 이전 filter에서 셋팅한 clientId 확보
			clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);

			// 이전 filter에서 셋팅한 값이 없다면 header 정보에서 확보
			if (StringUtils.isBlank(clientId)) {
				clientId = request.getHeader(HttpAdapterServiceSupport.HEADER_NAME_CLIENT_ID);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return clientId;
	}

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