package eu.dnetlib.data.collective.transformation.rulelanguage.util;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * @author jochen
 *
 */
public class Converter {

	private static final String xpathExpr = "xpath:\"";
	//private static final String labelExpr = "label:";
	
	public static String getXpathFromLabelExpr(String aElement){
		// TODO validate the argument -> consisting of 3 tokens, delimited by dot
		StringTokenizer tokenizer = new StringTokenizer(aElement, ".");
		List<String> tokenList = new LinkedList<String>();
		while (tokenizer.hasMoreTokens()){
			tokenList.add(tokenizer.nextToken());
		}
		StringBuilder builder = new StringBuilder();
		builder.append("//"); // the xpath-expr
		builder.append(tokenList.get(0) + ":"); // the namespace
		builder.append(tokenList.get(2)); // the elementname
		return builder.toString();
	}
	
	/**
	 * extracts a xpath-expression made in a production rule
	 * @param aElement
	 * @return xpath expression
	 */
	public static String getXpathFromXpathExpr(String aElement){
		String xpath = "";
		if (aElement.startsWith(xpathExpr)){
			xpath = aElement.substring(xpathExpr.length(), aElement.length() - 1);
		}
		return xpath;
	}
	
	public static boolean isXpathReturningString(String aXpathExpr){
		String[] functions = {"concat", "normalize-space", "translate", "substring"};
		for (String fct: functions)
			if (aXpathExpr.startsWith(fct)) return true;
		return false;
	}
	
	public static String getUnquotedString(String aValue){
		return aValue.substring(1, aValue.length() - 1);
	}
	
	/**
	 * returns a list of name-space declarations used in xsl
	 * @param nsPrefixMap - a map of name-space prefixes and their uris
	 * @return list of name-space declarations
	 */
	public static List<String> getBoundPrefixes(Map<String, String> nsPrefixMap){
		List<String> nsList = new LinkedList<String>();
		for (String key: nsPrefixMap.keySet()){
			nsList.add("xmlns:" + key + "=" + "\"" + nsPrefixMap.get(key) + "\" ");
		}
		return nsList;
	}
}
