package eu.dnetlib.conf;

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

import javax.servlet.ServletContext;

import org.apache.catalina.Container;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.commons.lang.reflect.FieldUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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<Properties> {

	/**
	 * 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 Properties 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 Properties.class;
	}

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

	private int getPort(final ServletContext servletContext) {
		try {
			return getContainerPort(servletContext);
		} catch (Throwable e) {
			log.warn("cannot obtain port from container...strange: I thought it would work both on jetty and tomcat7...)", e);
			return 0;
		}
	}

	private int getContainerPort(final ServletContext servletContext) {
		try {
			Object o = FieldUtils.readField(servletContext, "context", true);
			StandardContext sCtx = (StandardContext) FieldUtils.readField(o, "context", true);
			Container container = sCtx;

			Container c = container.getParent();
			while ((c != null) && !(c instanceof StandardEngine)) {
				c = c.getParent();
			}

			if (c != null) {
				StandardEngine engine = (StandardEngine) c;
				for (Connector connector : engine.getService().findConnectors()) {
					if (connector.getPort() > 0) return connector.getPort();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	private String getHost(final 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(final boolean resolveHostname) {
		this.resolveHostname = resolveHostname;
	}

	public PropertyFetcher getPropertyFetcher() {
		return propertyFetcher;
	}

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

}
