package net.sf.jasperreports.engine.fill;

class JRLongVarianceIncrementer extends JRAbstractExtendedIncrementer {
  private static JRLongVarianceIncrementer mainInstance = new JRLongVarianceIncrementer();
  
  public static JRLongVarianceIncrementer 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 JRLongIncrementerFactory.ZERO; 
    Number countValue = (Number)valueProvider.getValue(variable.getHelperVariable((byte)0));
    Number sumValue = (Number)valueProvider.getValue(variable.getHelperVariable((byte)1));
    return new Long((countValue.longValue() - 1L) * value.longValue() / countValue.longValue() + (sumValue.longValue() / countValue.longValue() - newValue.longValue()) * (sumValue.longValue() / countValue.longValue() - newValue.longValue()) / (countValue.longValue() - 1L));
  }
  
  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 Long(((Number)calculableValue.getIncrementedValue()).longValue()); 
    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 Long((long)(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 JRLongIncrementerFactory.ZERO;
  }
}
