package eu.dnetlib.springutils.template;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO: refactor: this is no more a pure dao!
 * 
 * @author marko
 *
 */
public class BeanTemplateDaoImpl implements BeanTemplateDao {
	Map<String, BeanTemplate> byName = new HashMap<String, BeanTemplate>();

	Map<String, List<TemplateInstance>> instances = new HashMap<String, List<TemplateInstance>>();
	
	@Override
	public BeanTemplate getTemplate(String name) {
		return byName.get(name);
	}

	@Override
	public void registerTemplate(BeanTemplate template) {
		byName.put(template.getName(), template);
		for(TemplateInstance instance : getInstancesForTemplate(template))
			instance.instantiate(template);
	}

	@Override
	public List<TemplateInstance> getInstancesForTemplate(BeanTemplate template) {
		return getInstancesForTemplate(template.getName());
	}
		
	public List<TemplateInstance> getInstancesForTemplate(String templateName) {
		List<TemplateInstance> list = instances.get(templateName);
		if(list == null)
			list = new ArrayList<TemplateInstance>();
		return list;
	}

	@Override
	public void registerTemplateInstance(TemplateInstance instance) {
		List<TemplateInstance> list = getInstancesForTemplate(instance.getTemplateName());	
		list.add(instance);
		instances.put(instance.getTemplateName(), list);
	}

}
