package eu.dnetlib.msro.workflows.util;

import java.util.List;
import java.util.Map;

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

import com.google.common.collect.Lists;

import eu.dnetlib.miscutils.functional.UnaryFunction;
import eu.dnetlib.msro.rmi.MSROException;
import eu.dnetlib.msro.workflows.util.ValidNodeValuesFetcher.DnetParamValue;

public abstract class ValidNodeValuesFetcher implements UnaryFunction<List<DnetParamValue>, Map<String, String>> {

	private String name;

	private static final Log log = LogFactory.getLog(ValidNodeValuesFetcher.class);

	public class DnetParamValue implements Comparable<DnetParamValue> {

		private String id;
		private String name;

		public DnetParamValue(final String id, final String name) {
			this.id = id;
			this.name = name;
		}

		public String getId() {
			return id;
		}

		public String getName() {
			return name;
		}

		@Override
		public int compareTo(final DnetParamValue o) {
			return getName().compareTo(o.getName());
		}
	}

	@Override
	final public List<DnetParamValue> evaluate(final Map<String, String> params) {
		try {
			return obtainValues(params);
		} catch (Throwable e) {
			log.error("Error obtaing values", e);
			return Lists.newArrayList();
		}
	}

	abstract protected List<DnetParamValue> obtainValues(Map<String, String> params) throws Exception;

	public String getName() {
		return name;
	}

	@Required
	public void setName(final String name) {
		this.name = name;
	}

	protected void verifyParams(final Map<String, String> params, final String... pnames) throws MSROException {
		for (String s : pnames) {
			if (!params.containsKey(s)) { throw new MSROException("Parameter not found: " + s); }
		}
	}
}
