package ru.yandex.webmaster3.storage.searchquery.util;

import ru.yandex.webmaster3.storage.searchquery.DayStat;

import java.util.function.Function;

/**
 * @author aherman
 */
public class DoubleSumAccumulator implements Function<DayStat, Void>, Accumulator {
    private final Function<DayStat, Double> valueExtractor;

    private boolean hasGaps = false;
    private Double sum = null;
    private int itemsCount = 0;

    public DoubleSumAccumulator(Function<DayStat, Double> valueExtractor) {
        this.valueExtractor = valueExtractor;
    }

    @Override
    public Void apply(DayStat stat) {
        Double v = valueExtractor.apply(stat);
        if (v == null || !Double.isFinite(v)) {
            hasGaps = true;
            return null;
        }
        if (sum == null) {
            sum = v;
        } else {
            sum += v;
        }
        itemsCount++;

        return null;
    }

    @Override
    public Double getValue() {
        return sum;
    }

    @Override
    public int getItemsCount() {
        return itemsCount;
    }

    @Override
    public boolean hasGaps() {
        return hasGaps;
    }

    @Override
    public String toString() {
        return "SUM[" + sum + "]";
    }

}
