package org.ambraproject.wombat.freemarker;

import com.google.common.base.Preconditions;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

public class RandomIntegerDirective implements TemplateDirectiveModel {

  private static final Integer DEFAULT_MIN = 0;
  private static final Integer DEFAULT_MAX = 10000;

  private final Random random = new Random();

  private static Integer asInteger(Object number, Integer defaultValue) throws TemplateModelException {
    if (number == null) return defaultValue;
    return ((TemplateNumberModel) number).getAsNumber().intValue();
  }

  @Override
  public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
      throws TemplateException, IOException {
    Integer minValue = asInteger(params.get("minValue"), DEFAULT_MIN);
    Integer maxValue = asInteger(params.get("maxValue"), DEFAULT_MAX);
    Preconditions.checkArgument(minValue < maxValue);

    int randomValue = random.nextInt(maxValue - minValue) + minValue;

    env.getOut().write(String.valueOf(randomValue));
  }

}

@@ -484,16 +484,135 @@
 andom;%0A%0A
+/**%0A * Generates an insecure random integer, between the params %22minValue%22 (inclusive) and %22maxValue%22 (exclusive).%0A */%0A
 public c
@@ -826,34 +826,458 @@
 m();
-%0A%0A  private static Integer
+ // needs SecureRandom if these numbers are used cryptographically%0A%0A  /**%0A   * Interpret a FreeMarker number as a primitive integer.%0A   *%0A   * @param number       a FreeMarker number value%0A   * @param defaultValue the value to use if %7B@code number == null%7D%0A   * @return the integer value%0A   * @throws TemplateModelException%0A   * @throws java.lang.ClassCastException if %7B@code number%7D is non-null and not a FreeMarker number%0A   */%0A  private static int
  asI
@@ -1298,23 +1298,19 @@
 number, 
-I
+i
 nt
-eger
  default
@@ -1633,23 +1633,19 @@
 n %7B%0A    
-I
+i
 nt
-eger
  minValu
@@ -1700,23 +1700,19 @@
 N);%0A    
-I
+i
 nt
-eger
  maxValu

Add comments to RandomIntegerDirective