package eu.dnetlib.data.collector.plugins.ariadneplus.isidore;

import eu.dnetlib.miscutils.functional.xml.SaxonHelper;
import eu.dnetlib.rmi.data.CollectorServiceException;
import eu.dnetlib.rmi.data.InterfaceDescriptor;
import eu.dnetlib.rmi.data.plugin.AbstractCollectorPlugin;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author alessia bardi
 *
 */
public class IsidoreCollectorPlugin extends AbstractCollectorPlugin {

	@Autowired
	private SaxonHelper saxonHelper;

	@Override
	public Iterable<String> collect(InterfaceDescriptor ifDescriptor, String arg1, String arg2)
			throws CollectorServiceException {
		final String baseUrl = ifDescriptor.getBaseUrl();
		final String queryParams = ifDescriptor.getParams().get("queryParams");
		final String pageParam = ifDescriptor.getParams().get("pageParam");
		final String startFromPage = ifDescriptor.getParams().get("startFromPage");
		final String nextPagePath = ifDescriptor.getParams().get("nextPagePath");
		final String pageSizeParam = ifDescriptor.getParams().get("pageSizeParam");
		final String pageSize = ifDescriptor.getParams().get("pageSize");
		final String resultTotalXpath = ifDescriptor.getParams().get("resultTotalXpath");
		final String entityXpath = ifDescriptor.getParams().get("entityXpath");
		
		if (StringUtils.isBlank(baseUrl)) {throw new CollectorServiceException("Param 'baseUrl' is null or empty");}
		if (StringUtils.isBlank(pageParam)) {throw new CollectorServiceException("Param 'pageParam' is null or empty");}
		if (StringUtils.isBlank(startFromPage)) {throw new CollectorServiceException("Param 'startFromPage' is null or empty");}
		if (StringUtils.isBlank(nextPagePath)) {throw new CollectorServiceException("Param 'nextPagePath' is null or empty");}
		if (StringUtils.isBlank(pageSizeParam)) {throw new CollectorServiceException("Param 'pageSizeParam' is null or empty");}
		if (StringUtils.isBlank(pageSize)) {throw new CollectorServiceException("Param 'pageSize' is null or empty");}
		if (StringUtils.isBlank(resultTotalXpath)) {throw new CollectorServiceException("Param 'resultTotalXpath' is null or empty");}
		if (StringUtils.isBlank(entityXpath)) {throw new CollectorServiceException("Param 'entityXpath' is null or empty");}

		return () -> new IsidoreIterator(
				saxonHelper,
				baseUrl,
				queryParams,
				pageParam,
				Integer.parseInt(startFromPage),
				nextPagePath,
				pageSizeParam,
				Integer.parseInt(pageSize),
				resultTotalXpath,
				entityXpath);
	}
}
