package eu.dnetlib.msro.workflows.sarasvati.loader;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.googlecode.sarasvati.Node;
import com.googlecode.sarasvati.load.DefaultNodeFactory;
import com.googlecode.sarasvati.load.SarasvatiLoadException;
import com.googlecode.sarasvati.mem.MemNode;

public class InjectableNodeFactory extends DefaultNodeFactory implements ApplicationContextAware {

	private String beanNamePrefix = "wfNode";

	private static final String DEFAULT_NODE_TYPE = "node";
	
	private transient ApplicationContext applicationContext;

	public InjectableNodeFactory() {
		super(MemNode.class);
	}

	public InjectableNodeFactory(final Class<? extends Node> defaultClass) {
		super(defaultClass);
	}

	@Override
	public Node newNode(final String type) throws SarasvatiLoadException {
		
		if (!DEFAULT_NODE_TYPE.equals(type)) {
			final Node prototypeNode = (Node) applicationContext.getBean(beanNamePrefix + type, Node.class);
			
			if (prototypeNode != null) {
				return prototypeNode;
			} else {
				throw new SarasvatiLoadException("cannot find bean " + beanNamePrefix + type);
			}
		}
		return super.newNode(type);
	}

	@Override
	public void setApplicationContext(final ApplicationContext context) {
		this.applicationContext = context;
	}

	public String getBeanNamePrefix() {
		return beanNamePrefix;
	}

	@Required
	public void setBeanNamePrefix(final String beanNamePrefix) {
		this.beanNamePrefix = beanNamePrefix;
	}

}