package eu.dnetlib.conf;

import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyResourceConfigurer;

/**
 * PropertyFletcher
 * 
 * @author marko
 * 
 */
public class PropertyFetcher extends PropertyResourceConfigurer implements InitializingBean {

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

	boolean unchangedHostname = false;
	boolean unchangedPort = true;

	private Properties props;

	@Override
	public void afterPropertiesSet() throws Exception {
		this.props = mergeProperties();

		// Convert the merged properties, if necessary.
		convertProperties(props);

		log.debug("FOUND A container.hostname property " + props.getProperty("container.hostname"));

		if ("localhost".equals(props.getProperty("container.hostname"))) {
			unchangedHostname = true;
		}
		if (props.getProperty("container.port") != null) {
			log.debug("FOUND A container.port property " + props.getProperty("container.port"));
			unchangedPort = false;
		}

		if (log.isDebugEnabled()) {
			log.debug("HOST unchanged? " + unchangedHostname);
			log.debug("PORT unchanged? " + unchangedPort);
			for (Entry<?, ?> e : props.entrySet()) {
				log.debug("system property: " + e.getKey() + " --> " + e.getValue());
			}
		}
	}

	@Override
	protected void processProperties(final ConfigurableListableBeanFactory arg0, final Properties props) throws BeansException {

	}

	public boolean isUnchangedHostname() {
		return unchangedHostname;
	}

	public void setUnchangedHostname(final boolean unchangedHostname) {
		this.unchangedHostname = unchangedHostname;
	}

	public boolean isUnchangedPort() {
		return unchangedPort;
	}

	public void setUnchangedPort(final boolean unchangedPort) {
		this.unchangedPort = unchangedPort;
	}

	public String getProperty(final String key) {
		return props.getProperty(key);
	}

	public Properties getProps() {
		return props;
	}

	public void setProps(final Properties props) {
		this.props = props;
	}

}
