package eu.dnetlib.data.collector.functions;

import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Required;

import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;

import eu.dnetlib.data.collector.plugins.oaisets.OaiSetsIteratorFactory;
import eu.dnetlib.data.collector.rmi.ProtocolParameterValue;

public class ListOaiSetsFunction implements ParamValuesFunction {

	private OaiSetsIteratorFactory oaiSetsIteratorFactory;

	@Override
	public List<ProtocolParameterValue> findValues(final String baseUrl, final Map<String, String> params) {
		final SAXReader reader = new SAXReader();

		final Iterator<ProtocolParameterValue> iter = Iterators.transform(oaiSetsIteratorFactory.newIterator(baseUrl),
				new Function<String, ProtocolParameterValue>() {

					@Override
					public ProtocolParameterValue apply(final String s) {
						try {
							final Document doc = reader.read(new StringReader(s));
							final String id = doc.valueOf("//*[local-name()='setSpec']");
							final String name = doc.valueOf("//*[local-name()='setName']");
							return new ProtocolParameterValue(id,
									(StringUtils.isBlank(name) || name.equalsIgnoreCase(id)) ? id : id + " - name: \"" + name + "\"");
						} catch (final DocumentException e) {
							throw new RuntimeException("Error in ListSets", e);
						}
					}
				});
		return Lists.newArrayList(iter);
	}

	public OaiSetsIteratorFactory getOaiSetsIteratorFactory() {
		return oaiSetsIteratorFactory;
	}

	@Required
	public void setOaiSetsIteratorFactory(final OaiSetsIteratorFactory oaiSetsIteratorFactory) {
		this.oaiSetsIteratorFactory = oaiSetsIteratorFactory;
	}
}
