package net.sf.jasperreports.engine.fill;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExpression;
import net.sf.jasperreports.engine.JRHyperlink;
import net.sf.jasperreports.engine.JRHyperlinkParameter;
import net.sf.jasperreports.engine.JRPrintHyperlink;
import net.sf.jasperreports.engine.JRPrintHyperlinkParameter;
import net.sf.jasperreports.engine.JRPrintHyperlinkParameters;
import net.sf.jasperreports.engine.base.JRBasePrintHyperlink;

public class JRFillHyperlinkHelper {
  public static JRPrintHyperlinkParameters evaluateHyperlinkParameters(JRHyperlink hyperlink, JRFillExpressionEvaluator expressionEvaluator, byte evaluationType) throws JRException {
    JRPrintHyperlinkParameters printParameters;
    JRHyperlinkParameter[] hyperlinkParameters = hyperlink.getHyperlinkParameters();
    if (hyperlinkParameters == null) {
      printParameters = null;
    } else {
      printParameters = new JRPrintHyperlinkParameters();
      for (int i = 0; i < hyperlinkParameters.length; i++) {
        Class valueClass;
        Object value;
        JRHyperlinkParameter hyperlinkParameter = hyperlinkParameters[i];
        JRExpression valueExpression = hyperlinkParameter.getValueExpression();
        if (valueExpression == null) {
          value = null;
          valueClass = Object.class;
        } else {
          value = expressionEvaluator.evaluate(valueExpression, evaluationType);
          valueClass = valueExpression.getValueClass();
        } 
        JRPrintHyperlinkParameter printParam = new JRPrintHyperlinkParameter(hyperlinkParameter.getName(), valueClass.getName(), value);
        printParameters.addParameter(printParam);
      } 
    } 
    return printParameters;
  }
  
  public static JRPrintHyperlink evaluateHyperlink(JRHyperlink hyperlink, JRFillExpressionEvaluator expressionEvaluator, byte evaluationType) throws JRException {
    JRBasePrintHyperlink printHyperlink = new JRBasePrintHyperlink();
    printHyperlink.setLinkType(hyperlink.getLinkType());
    printHyperlink.setHyperlinkTarget(hyperlink.getHyperlinkTarget());
    printHyperlink.setHyperlinkReference((String)expressionEvaluator.evaluate(hyperlink.getHyperlinkReferenceExpression(), evaluationType));
    printHyperlink.setHyperlinkAnchor((String)expressionEvaluator.evaluate(hyperlink.getHyperlinkAnchorExpression(), evaluationType));
    printHyperlink.setHyperlinkPage((Integer)expressionEvaluator.evaluate(hyperlink.getHyperlinkPageExpression(), evaluationType));
    printHyperlink.setHyperlinkTooltip((String)expressionEvaluator.evaluate(hyperlink.getHyperlinkTooltipExpression(), evaluationType));
    printHyperlink.setHyperlinkParameters(evaluateHyperlinkParameters(hyperlink, expressionEvaluator, evaluationType));
    return (JRPrintHyperlink)printHyperlink;
  }
}
