package ru.yandex.webmaster3.storage.searchquery;

import java.util.Iterator;
import java.util.Map;

import com.google.common.collect.Range;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.LocalDate;

/**
 * @author aherman
 */
public class MapWithDiff {
    public static void map(Iterator<Pair<Range<LocalDate>, Double>> it, Mapper mapper) {
        map(it, false, mapper);
    }

    public static void map(Iterator<Pair<Range<LocalDate>, Double>> it, boolean ignoreEmptyPrevious, Mapper mapper) {
        Map.Entry<Range<LocalDate>, Double> previousEntry = null;
        while (it.hasNext()) {
            Map.Entry<Range<LocalDate>, Double> currentEntry = it.next();
            if (previousEntry != null || ignoreEmptyPrevious) {
                Double diff = computeDiff(currentEntry.getValue(), previousEntry == null ? null : previousEntry.getValue());
                mapper.map(currentEntry.getKey(), currentEntry.getValue(), diff);
            }
            previousEntry = currentEntry;
        }
    }

    // null -> null = null
    // null -> value = null
    // value1 -> value2 = value2 - value1
    // value -> null = null
    private static Double computeDiff(Double current, Double previous) {
        if (previous == null || current == null) {
            return null;
        }
        return current - previous;
    }

    public static interface Mapper {
        public void map(Range<LocalDate> range, Double currentValue, Double diff);
    }
}
