package eu.dnetlib.enabling.tools;

import java.util.Map;

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


/**
 * This bean has to live in the same bean factory where all schedulables live. Thus it cannot be put inside the
 * EnableablController, which lives in the webContext.
 * 
 * @author claudio
 * 
 */
public class SchedulableEnumerator implements BeanFactoryAware {

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

	/**
	 * Get all beans implementing the Schedulable interface.
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Schedulable> getAllSchedulables() {
		return beanFactory.getBeansOfType(Schedulable.class);
	}

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

	public ListableBeanFactory getBeanFactory() {
		return beanFactory;
	}

	/**
	 * Get given schedulable or null.
	 * 
	 * @param name
	 * @return
	 */
	public Schedulable getSchedulable(final String name) {
		try {
			return (Schedulable) beanFactory.getBean(name, Schedulable.class);
		} catch (final NoSuchBeanDefinitionException e) {
			return null;
		}
	}

}
