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

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

/**
 * @author js
 *
 */
public class Split extends AbstractTransformationFunction {

	public static final Log log = LogFactory.getLog(Split.class);
	public static final String paramInputExpr = "inputExpr";
	public static final String paramRegExpr = "regExpr";
	public static final String paramElementName = "elementName";
	
	private Map<String, Queue<String>> queueMap = new HashMap<String, Queue<String>>();
	
	/* (non-Javadoc)
	 * @see eu.dnetlib.data.collective.transformation.engine.functions.AbstractTransformationFunction#execute()
	 */
	@Override
	String execute() throws ProcessingException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * split a given list of values using a delimiter as regularExpression
	 * @param aInputValue
	 * @param aRegExpr
	 * @return the collection of all values splitted
	 */
	public Collection<String> executeAllValues(List<String> aInputValues, String aRegExpr) throws ProcessingException{
		Collection<String> result = new LinkedList<String>();
		for (String value: aInputValues){
			String[] values = StringUtils.tokenizeToStringArray(value, aRegExpr, true, true);				
			result.addAll(Arrays.asList(values));
		}			
		return result;
	}
	
	/**
	 * split a given list of values stored in an internal queue and return the element from the head of the queue (recursive)
	 * @param aInputValues
	 * @param aRegExpr
	 * @param aCallId
	 * @return
	 * @throws ProcessingException
	 */
	public String executeSingleValue(List<String> aInputValues, String aRegExpr, String aCallId) throws ProcessingException{
		if (!queueMap.containsKey(aCallId)){
			Queue<String> queue = new LinkedList<String>();
			queueMap.put(aCallId, queue);
			for (String value: aInputValues){
				String[] values = StringUtils.tokenizeToStringArray(value, aRegExpr, true, true);				
				queue.addAll(Arrays.asList(values));
			}			
		}
		String result = queueMap.get(aCallId).poll();
		if (result == null){
			queueMap.remove(aCallId);
		}
		return result;
	}
	
	public String executeSingleValue(String aCallId) throws ProcessingException{
		String result = queueMap.get(aCallId).poll();
		if (result == null){
			queueMap.remove(aCallId);
		}
		return result;
	}
}
