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

import java.util.function.Function;

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

/**
 * @author aherman
 */
public class WeightedAvgPositionAccumulator implements Accumulator {
    private Long sumPositions;
    private Long value;

    private final Function<DayStat, Long> sumPositionsExtractor;
    private final Function<DayStat, Long> valueExtractor;

    public WeightedAvgPositionAccumulator(Function<DayStat, Long> valueExtractor,
            Function<DayStat, Long> sumPositionsExtractor)
    {
        this.sumPositionsExtractor = sumPositionsExtractor;
        this.valueExtractor = valueExtractor;
    }

    @SuppressWarnings("Duplicates")
    @Override
    public Void apply(DayStat stat) {
        Long sp = sumPositionsExtractor.apply(stat);
        Long v = valueExtractor.apply(stat);
        if (sp == null && v == null) {
            return null;
        }
        if (sumPositions == null) {
            sumPositions = 0L;
        }
        if (value == null) {
            value = 0L;
        }
        if (sp != null) {
            sumPositions += sp;
        }
        if (v != null) {
            value += v;
        }
        return null;
    }

    @Override
    public Double getValue() {
        if (sumPositions == null || value == null) {
            return null;
        }

        if (value > 0 ) {
            return sumPositions * 1.0 / value;
        }

        return null;
    }

    @Override
    public String toString() {
        return "AVG_POS[" + sumPositions + "/" + value + "]";
    }
}
