package cn.gov.jscd.experts.interceptors;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class BaseInterception implements HandlerInterceptor {

	private static String BASE = StringUtils.EMPTY;

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		if (StringUtils.isBlank(BASE)) {
			BASE = this.concatBase(request);
		}
		request.setAttribute("base", BASE);
		return true;
	}

	private String concatBase(HttpServletRequest request) {
		StringBuffer buffer = new StringBuffer(request.getScheme()).append("://");
		String server = request.getServerName();
		if(StringUtils.equalsAny(server, "localhost", "127.0.0.1")) {
			String local = this.getServerIp();
			if(StringUtils.isNotBlank(local)) {
				server = local;
			}
		}
		
		buffer.append(server);
		int port = request.getServerPort();
		if (port != 80) {
			buffer.append(":").append(port);
		}
		buffer.append(request.getContextPath()).append("/");

		return buffer.toString();
	}

	@SuppressWarnings("rawtypes")
	public String getServerIp() {
		String SERVER_IP = null;
		try {
			Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
				ip = (InetAddress) ni.getInetAddresses().nextElement();
				SERVER_IP = ip.getHostAddress();
				if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
					SERVER_IP = ip.getHostAddress();
					break;
				} else {
					ip = null;
				}
			}
		} catch (SocketException e) {}

		return SERVER_IP;
	}
}