package eu.dnetlib.data.collector;

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

import javax.annotation.Resource;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import eu.dnetlib.data.collector.plugin.CollectorPlugin;
import eu.dnetlib.data.collector.rmi.CollectorService;
import eu.dnetlib.data.collector.rmi.CollectorServiceException;
import eu.dnetlib.data.collector.rmi.InterfaceDescriptor;
import eu.dnetlib.data.collector.rmi.ProtocolDescriptor;
import eu.dnetlib.data.collector.rmi.ProtocolParameter;
import eu.dnetlib.data.collector.rmi.ProtocolParameterValue;
import eu.dnetlib.enabling.resultset.IterableResultSetFactory;
import eu.dnetlib.enabling.tools.AbstractBaseService;

public class CollectorServiceImpl extends AbstractBaseService implements CollectorService {

	@Resource
	private CollectorPluginEnumerator collectorPluginEnumerator;

	@Resource
	private IterableResultSetFactory iterableResultSetFactory;

	@Override
	public W3CEndpointReference collect(final InterfaceDescriptor ifDescriptor) throws CollectorServiceException {
		return dateRangeCollect(ifDescriptor, null, null);
	}

	@Override
	public W3CEndpointReference dateRangeCollect(
			final InterfaceDescriptor ifDescriptor, final String from, final String until)
			throws CollectorServiceException {
		final CollectorPlugin plugin = collectorPluginEnumerator.get(ifDescriptor.getProtocol());

		if (!verifyParams(ifDescriptor.getParams().keySet(), Sets.newHashSet(plugin.listNameParameters()))) { throw new CollectorServiceException(
				"Invalid parameters, valid: " + plugin.listNameParameters() + ", current: " + ifDescriptor.getParams().keySet()); }

		final Iterable<String> iter = plugin.collect(ifDescriptor, from, until);

		return iterableResultSetFactory.createIterableResultSet(iter);
	}

	@Override
	public List<ProtocolDescriptor> listProtocols() {
		final List<ProtocolDescriptor> list = Lists.newArrayList();
		for (CollectorPlugin plugin : collectorPluginEnumerator.getAll()) {
			list.add(plugin.getProtocolDescriptor());
		}
		return list;
	}

	@Override
	public List<ProtocolParameterValue> listValidValuesForParam(final String protocol,
			final String baseUrl,
			final String param,
			final Map<String, String> otherParams) throws CollectorServiceException {
		final CollectorPlugin plugin = collectorPluginEnumerator.get(protocol);

		for (ProtocolParameter pp : plugin.getProtocolDescriptor().getParams()) {
			if (pp.getName().equals(param) && pp.isFunctionPopulated()) { return pp.getPopulateFunction().findValues(baseUrl, otherParams); }
		}

		return Lists.newArrayList();
	}

	private boolean verifyParams(final Set<String> curr, final Set<String> valid) {
		return valid.containsAll(curr);
	}

}
