package net.sf.jasperreports.engine.util;

import net.sf.jasperreports.engine.JRCommonText;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRPropertiesHolder;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.fill.JRTextMeasurer;
import net.sf.jasperreports.engine.fill.JRTextMeasurerFactory;

public class JRTextMeasurerUtil {
  public static final String PROPERTY_TEXT_MEASURER_FACTORY = "net.sf.jasperreports.text.measurer.factory";
  
  private static final JRSingletonCache cache = new JRSingletonCache(JRTextMeasurerFactory.class);
  
  public static JRTextMeasurer createTextMeasurer(JRCommonText text) {
    JRPropertiesHolder propertiesHolder = (text instanceof JRPropertiesHolder) ? (JRPropertiesHolder)text : null;
    return createTextMeasurer(text, propertiesHolder);
  }
  
  public static JRTextMeasurer createTextMeasurer(JRCommonText text, JRPropertiesHolder propertiesHolder) {
    JRTextMeasurerFactory factory = getTextMeasurerFactory(propertiesHolder);
    return factory.createMeasurer(text);
  }
  
  public static JRTextMeasurerFactory getTextMeasurerFactory(JRPropertiesHolder propertiesHolder) {
    String factoryClass = getTextMeasurerFactoryClass(propertiesHolder);
    try {
      return (JRTextMeasurerFactory)cache.getCachedInstance(factoryClass);
    } catch (JRException e) {
      throw new JRRuntimeException(e);
    } 
  }
  
  protected static String getTextMeasurerFactoryClass(JRPropertiesHolder propertiesHolder) {
    String factory = JRProperties.getProperty(propertiesHolder, "net.sf.jasperreports.text.measurer.factory");
    String factoryClassProperty = "net.sf.jasperreports.text.measurer.factory." + factory;
    String factoryClass = JRProperties.getProperty(propertiesHolder, factoryClassProperty);
    if (factoryClass == null)
      factoryClass = factory; 
    return factoryClass;
  }
}
