package net.sf.jasperreports.engine.fill;

class JRIntegerVarianceIncrementer extends JRAbstractExtendedIncrementer {
  private static JRIntegerVarianceIncrementer mainInstance = new JRIntegerVarianceIncrementer();
  
  public static JRIntegerVarianceIncrementer getInstance() {
    return mainInstance;
  }
  
  public Object increment(JRCalculable variable, Object expressionValue, AbstractValueProvider valueProvider) {
    Number value = (Number)variable.getIncrementedValue();
    Number newValue = (Number)expressionValue;
    if (newValue == null) {
      if (variable.isInitialized())
        return null; 
      return value;
    } 
    if (value == null || variable.isInitialized())
      return JRIntegerIncrementerFactory.ZERO; 
    Number countValue = (Number)valueProvider.getValue(variable.getHelperVariable((byte)0));
    Number sumValue = (Number)valueProvider.getValue(variable.getHelperVariable((byte)1));
    return new Integer((countValue.intValue() - 1) * value.intValue() / countValue.intValue() + (sumValue.intValue() / countValue.intValue() - newValue.intValue()) * (sumValue.intValue() / countValue.intValue() - newValue.intValue()) / (countValue.intValue() - 1));
  }
  
  public Object combine(JRCalculable calculable, JRCalculable calculableValue, AbstractValueProvider valueProvider) {
    Number value = (Number)calculable.getIncrementedValue();
    if (calculableValue.getValue() == null) {
      if (calculable.isInitialized())
        return null; 
      return value;
    } 
    if (value == null || calculable.isInitialized())
      return new Integer(((Number)calculableValue.getIncrementedValue()).intValue()); 
    double v1 = value.doubleValue();
    double c1 = ((Number)valueProvider.getValue(calculable.getHelperVariable((byte)0))).doubleValue();
    double s1 = ((Number)valueProvider.getValue(calculable.getHelperVariable((byte)1))).doubleValue();
    double v2 = ((Number)calculableValue.getIncrementedValue()).doubleValue();
    double c2 = ((Number)valueProvider.getValue(calculableValue.getHelperVariable((byte)0))).doubleValue();
    double s2 = ((Number)valueProvider.getValue(calculableValue.getHelperVariable((byte)1))).doubleValue();
    c1 -= c2;
    s1 -= s2;
    double c = c1 + c2;
    return new Integer((int)(c1 / c * v1 + c2 / c * v2 + c2 / c1 * s1 / c * s1 / c + c1 / c2 * s2 / c * s2 / c - 2.0D * s1 / c * s2 / c));
  }
  
  public Object initialValue() {
    return JRIntegerIncrementerFactory.ZERO;
  }
}
