package eu.dnetlib.springutils.condbean;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This is the original implementation of Robert Maldon's property expression parser, factored out in a
 * ConditionExpressionParser so that we can easly replace it with a more powerful parser.
 * 
 * @see JParsecConditionExpression
 * 
 * @author marko
 * 
 */
public class TrivialConditionExpressionParser implements ConditionExpressionParser {
	private static final Log log = LogFactory.getLog(TrivialConditionExpressionParser.class); // NOPMD by marko on 11/24/08 5:02 PM

	/** Default placeholder prefix: "${". */
	public static final String PH_PREFIX = "${";

	/** Default placeholder suffix: "}". */
	public static final String PH_SUFFIX = "}";

	public boolean expressionValue(final String expression) {
		log.debug("EXPRESSION: " + expression);
		log.debug("EXPRESSION VALUE: " + getProperty(expression));
		return !StringUtils.isEmpty(getProperty(expression));
	}

	protected String getProperty(final String strVal) {
		if (StringUtils.isEmpty(strVal))
			return null;

		if (strVal.startsWith(PH_PREFIX) && strVal.endsWith(PH_SUFFIX))
			return basicGetProperty(strVal.substring(PH_PREFIX.length(), strVal.length() - PH_SUFFIX.length()));

		return basicGetProperty(strVal);
	}

	protected String basicGetProperty(final String name) {
		// TODO: merge properties from many files (wildcards) and provide a configuration
		final Properties props = new Properties();
		try {
			final InputStream input = TrivialConditionExpressionParser.class.getResourceAsStream("/eu/dnetlib/cnr-default.properties");
			if (input == null)
				log.warn("cannot open properties (null)");
			else
				props.load(input);

		} catch (IOException e) {
			log.warn("cannot open properties", e);
		}
		final String res = props.getProperty(name);
		if (res != null && !res.isEmpty())
			return res;

		return System.getProperty(name);
	}

}
