package net.sf.jasperreports.engine.fill;

import java.util.HashSet;
import java.util.Set;

class JRDistinctCountExtendedIncrementer extends JRAbstractExtendedIncrementer {
  private DistinctCountHolder lastHolder = new DistinctCountHolder();
  
  public Object increment(JRCalculable variable, Object expressionValue, AbstractValueProvider valueProvider) {
    DistinctCountHolder holder = (DistinctCountHolder)variable.getIncrementedValue();
    if (holder == null) {
      holder = this.lastHolder;
    } else {
      this.lastHolder = holder;
    } 
    holder.addLastValue();
    return new DistinctCountHolder(holder, expressionValue);
  }
  
  public Object combine(JRCalculable calculable1, JRCalculable calculable2, AbstractValueProvider valueProvider) {
    Set distinctValues = new HashSet();
    DistinctCountHolder holder1 = (DistinctCountHolder)calculable1.getValue();
    if (holder1 != null) {
      distinctValues.addAll(holder1.getDistinctValues());
      if (holder1.getLastValue() != null)
        distinctValues.add(holder1.getLastValue()); 
    } 
    DistinctCountHolder holder2 = (DistinctCountHolder)calculable2.getValue();
    if (holder2 != null) {
      distinctValues.addAll(holder2.getDistinctValues());
      if (holder2.getLastValue() != null)
        distinctValues.add(holder2.getLastValue()); 
    } 
    return new DistinctCountHolder(distinctValues);
  }
  
  public Object initialValue() {
    return null;
  }
}
