package eu.dnetlib.conf;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;

/**
 * This class wraps a list of property file paths and expands the @{webapp} placeholder with the name of the webapp taken from servlet-api
 * 2.5.
 * 
 * @author marko
 * 
 */
public class WebappContextPropertyLocationFactory extends AbstractWebappContextProperty implements FactoryBean<List<String>> {

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

	private List<String> locations;

	@Override
	public List<String> getObject() throws Exception {
		List<String> expanded = new ArrayList<String>();

		for (String loc : locations) {
			expanded.add(expand(loc).trim());
		}

		if (log.isInfoEnabled()) {
			for (String location : expanded) {
				log.info("Searching property file: " + location);
			}
		}

		return expanded;
	}

	private String expand(final String loc) {
		if (getContext() == null) return loc;
		return loc.replace("@{webapp}", getContext());
	}

	@Override
	public Class<?> getObjectType() {
		return locations.getClass();
	}

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

	public List<String> getLocations() {
		return locations;
	}

	public void setLocations(final List<String> locations) {
		this.locations = locations;
	}

}
