package leigh.conflux.nodegraph;

import leigh.eo.EO;
import leigh.mecha.nodegraph.ProcessorState;

import java.io.Serializable;
import java.math.BigDecimal;

public class AverageNode extends AggregateNode {
    public static final String TYPE = "avg";
    BigDecimal value;
    int count;

    public AverageNode(String id) {
        super(id);
    }

    @Override
    public void start(ProcessorState state) {
        count = 0;
        value = BigDecimal.ZERO;
    }

    @Override
    public void processRow(EO row, String key, ProcessorState state) throws Exception {
        BigDecimal x = row.getValueBigDecimal(key);
        count++;
        if (x != null)
            value = value.add(x);
    }

    @Override
    public Serializable finish(ProcessorState state) {
        if (count == 0) return null;
        return value.divide(BigDecimal.valueOf(count));
    }
}
