/*******************************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ******************************************************************************/
// Package
package gov.va.med.fw.service.config;

// Java classes
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;

// Library classes
import org.apache.commons.lang.Validate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.BeanFactoryAware;

// Framework classes

// ESR classes

/**
 * Project: Framework</br> Created on: 9:35:04 PM </br>
 * 
 * @author DNS   LEV
 */
public class MapFactoryCreatingFactoryBean extends AbstractFactoryBean implements BeanFactoryAware {

	private List targetBeanNames;

	private BeanFactory beanFactory;

	/**
	 * A default constructor
	 */
	public MapFactoryCreatingFactoryBean() {
		super();
	}

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	/**
	 * Set the source List, typically populated via XML "list" elements.
	 */
	public void setTargetBeanNames(List beanNames) {
		this.targetBeanNames = beanNames;
	}

	public Class getObjectType() {
		return ObjectFactory.class;
	}

	protected Object createInstance() {
		return new ObjectFactory() {
			public Object getObject() {
				Validate.notEmpty( targetBeanNames, "Target Bean Name List is required");

				Map beans = new HashMap();
				for( Iterator i=targetBeanNames.iterator(); i.hasNext(); ) {
					Object value = i.next();
					Validate.isTrue( (value instanceof String), "A bean name must be a string" );
					beans.put( (String)value, beanFactory.getBean( (String)value) );
				}
				return beans;
			}
		};
	}
}
