/**
 * 
 */
package eu.dnetlib.data.collective.transformation.engine.functions;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oro.text.perl.MalformedPerl5PatternException;
import org.apache.oro.text.perl.Perl5Util;

/**
 * @author jochen
 *
 */
public class RegularExpression extends AbstractTransformationFunction {

	public static final Log log = LogFactory.getLog(RegularExpression.class);
	public static final String paramRegularExpr = "regularExpression";
	public static final String paramExpr1		= "expr1";
	public static final String paramExpr2		= "expr2";
	
	private Perl5Util util = new Perl5Util();

	/* (non-Javadoc)
	 * @see eu.dnetlib.data.collective.transformation.engine.functions.AbstractTransformationFunction#execute()
	 */
	@Override
	String execute() throws ProcessingException {
		// TODO Auto-generated method stub
		return null;
	}
	
	public String executeSingleValue(String aRegularExpression, String aExpr1, String aExpr2) throws ProcessingException{
		String result = "";
		if (aRegularExpression.startsWith("m/")){
			if (util.match(aRegularExpression, aExpr1))
				result = util.group(1);
		}else if (!aRegularExpression.startsWith("s/")){ 
			// assume match and extract
			// throw new ProcessingException("unsupported or invalid regular expression: " + aRegularExpression);
			if (util.match(aRegularExpression, aExpr1)){
				String funder = util.group(1).toLowerCase();
				String projectId = util.group(3);
				result = funder + "_" + projectId;
			}
		}else{
			try{
				result = util.substitute(aRegularExpression, aExpr1);							
			}catch(MalformedPerl5PatternException patternExc){
				log.fatal("aRegularExpression: " + aRegularExpression);
				log.fatal("aExpr1: " + aExpr1);
				log.fatal(patternExc.getMessage());
				throw new ProcessingException(patternExc);
			}
		}
		return result;
	}

	
}
