package eu.dnetlib.conf;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.handler.ContextHandler;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Required;

/**
 * This factory generates default properties based on the amount of information available from the servlet container.
 * 
 * @author marko
 * 
 */
public class WebappContextProperyFactory extends AbstractWebappContextProperty implements FactoryBean {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(WebappContextProperyFactory.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * If false, the ip address will be returned, otherwise a best effort attemp will be made to retrieve a meaningful
	 * host name. There is a risk that the hostname is obtained without domain and thus completely useless.
	 */
	private boolean resolveHostname = false;

	private PropertyFetcher propertyFetcher;

	@Override
	public Object getObject() throws Exception {
		Properties props = new Properties();

		if (getContext() == null)
			return props;

		props.setProperty("container.context", getContext());

		log.debug("trying to autodetect port and hostame");

		// if the user didn't customize, then autodetect, otherwise honour the user!
		if (propertyFetcher.isUnchangedPort()) {
			log.debug("PORT IS NOT OVERRIDDEN, autodetecting");
			int port = getPort(getServletContext());
			if (port > 0)
				props.setProperty("container.port", Integer.toString(port));
		} else {
			log.debug("PORT IS OVERRIDDEN, NOT autodetecting");
		}

		if (propertyFetcher.isUnchangedHostname()) {
			log.debug("HOST IS NOT OVERRIDDEN, autodetecting");
			String hostname = getHost(getServletContext());
			if (hostname != null)
				props.setProperty("container.hostname", hostname);
		} else {
			log.debug("HOST IS OVERRIDDEN, NOT autodetecting");
		}

		return props;
	}

	@Override
	public Class<?> getObjectType() {
		return null;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	private int getPort(ServletContext servletContext) {
		try {
			return getJettyPort(servletContext);
		} catch (Throwable e) {
			log.warn("cannot obtain port from jetty container, probably not running inside jetty", e);
			return 0;
		}
	}

	private int getJettyPort(ServletContext servletContext) {
		Connector[] connectors = ((ContextHandler.SContext) servletContext).getContextHandler().getServer().getConnectors();
		for (Connector connector : connectors) {
			if (connector.getPort() > 0)
				return connector.getPort();
		}
		return 0;
	}

	private String getHost(ServletContext servletContext) {
		try {
			if (resolveHostname)
				return InetAddress.getLocalHost().getCanonicalHostName();
			else
				return InetAddress.getLocalHost().toString().split("/")[1];
		} catch (UnknownHostException e) {
			log.warn("cannot obtain hostname from JVM", e);
		}

		return null;
	}

	public boolean isResolveHostname() {
		return resolveHostname;
	}

	public void setResolveHostname(boolean resolveHostname) {
		this.resolveHostname = resolveHostname;
	}

	public PropertyFetcher getPropertyFetcher() {
		return propertyFetcher;
	}

	@Required
	public void setPropertyFetcher(PropertyFetcher propertyFetcher) {
		this.propertyFetcher = propertyFetcher;
	}

}
