package net.sf.jasperreports.engine.fill;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRPrintImage;
import net.sf.jasperreports.engine.JRRenderable;
import net.sf.jasperreports.engine.JasperPrint;
import org.apache.commons.collections.ReferenceMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class JRVirtualizationContext implements Serializable {
  private static final long serialVersionUID = 10200L;
  
  private static final Log log = LogFactory.getLog(JRVirtualizationContext.class);
  
  private static final ReferenceMap contexts = new ReferenceMap(2, 2);
  
  private Map cachedRenderers = new HashMap();
  
  private Map cachedTemplates = new HashMap();
  
  private boolean readOnly;
  
  public void cacheRenderer(JRPrintImage image) {
    JRRenderable renderer = image.getRenderer();
    if (renderer != null)
      this.cachedRenderers.put(renderer.getId(), renderer); 
  }
  
  public JRRenderable getCachedRenderer(String id) {
    return (JRRenderable)this.cachedRenderers.get(id);
  }
  
  public boolean hasCachedRenderer(String id) {
    return this.cachedRenderers.containsKey(id);
  }
  
  public boolean hasCachedTemplate(String id) {
    return this.cachedTemplates.containsKey(id);
  }
  
  public void cacheTemplate(JRTemplateElement template) {
    Object old = this.cachedTemplates.put(template.getId(), template);
    if (old == null && log.isDebugEnabled())
      log.debug("Cached template " + template + " having id " + template.getId()); 
  }
  
  public JRTemplateElement getCachedTemplate(String templateId) {
    return (JRTemplateElement)this.cachedTemplates.get(templateId);
  }
  
  public boolean isReadOnly() {
    return this.readOnly;
  }
  
  public void setReadOnly(boolean readOnly) {
    this.readOnly = readOnly;
  }
  
  public static void register(JRVirtualizationContext context, JasperPrint print) {
    synchronized (contexts) {
      contexts.put(print, context);
    } 
  }
  
  public static JRVirtualizationContext getRegistered(JasperPrint print) {
    synchronized (contexts) {
      return (JRVirtualizationContext)contexts.get(print);
    } 
  }
}
