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 enableables live. Thus it cannot be put inside the
 * EnableablController, which lives in the webContext.
 * 
 * @author marko
 * 
 */
public class EnableableEnumerator implements BeanFactoryAware {

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

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

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

	public ListableBeanFactory getBeanFactory() {
		return beanFactory;
	}

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

}
