package eu.dnetlib.data.collector;

import java.util.Collection;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;

import eu.dnetlib.data.collector.plugin.CollectorPlugin;
import eu.dnetlib.data.collector.rmi.CollectorServiceException;

public class CollectorPluginEnumerator implements BeanFactoryAware {

	// private static final Log log = LogFactory.getLog(CollectorPluginEnumerator.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * bean factory.
	 */
	private ListableBeanFactory beanFactory;

	/**
	 * Get all beans implementing the CollectorPlugin interface.
	 * 
	 * @return the set of eu.dnetlib.data.collector.plugin.CollectorPlugin(s)
	 */
	public Collection<CollectorPlugin> getAll() {
		return beanFactory.getBeansOfType(CollectorPlugin.class).values();
	}

	@Override
	public void setBeanFactory(final BeanFactory beanFactory) throws BeansException {
		this.beanFactory = (ListableBeanFactory) beanFactory;
	}

	public ListableBeanFactory getBeanFactory() {
		return beanFactory;
	}

	/**
	 * Get given CollectorPlugin or throws exception.
	 * 
	 * @param protocol the given protocol
	 * @return a CollectorPlugin compatible with the given protocol
	 * @throws CollectorServiceException when no suitable plugin is found
	 */
	public CollectorPlugin get(final String protocol) throws CollectorServiceException {
		for (CollectorPlugin cp : getAll()) {
			if (protocol.equalsIgnoreCase(cp.getProtocol())) {
				return cp;
			}
		}
		throw new CollectorServiceException("plugin not found for protocol: " + protocol);
	}
}
