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

import ru.yandex.webmaster3.core.searchquery.QueryIndicator;
import ru.yandex.webmaster3.core.searchquery.viewer.ViewerQueryGroup;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * Created by ifilippov5 on 06.03.17.
 */
public class GroupComparators {
    public static Comparator<QueryGroupStatistics> SPECIAL_GROUPS_FIRST =
            Comparator.comparing(QueryGroupStatistics::getGroup, ViewerQueryGroup.SPECIAL_GROUPS_FIRST);

    public static Comparator<QueryGroupStatistics> comparatorByIndicator(QueryIndicator orderBy) {
        return (g1, g2) -> {
            Optional<QueryIndicatorStatistics> i1O =
                    g1.getIndicators().stream().filter(i -> i.getName() == orderBy).findFirst();
            Optional<QueryIndicatorStatistics> i2O =
                    g2.getIndicators().stream().filter(i -> i.getName() == orderBy).findFirst();
            if (!i1O.isPresent() || !i2O.isPresent()) {
                return 0;
            }

            List<RangeStatistics> r1 = i1O.get().getRanges();
            List<RangeStatistics> r2 = i2O.get().getRanges();
            return compareRanges(r1, r2);
        };
    }

    public static Comparator<QueryGroupStatistics> comparatorByIndicator() {
        return (g1, g2) -> {
            List<RangeStatistics> r1 = g1.getIndicator().getRanges();
            List<RangeStatistics> r2 = g2.getIndicator().getRanges();
            return compareRanges(r1, r2);
        };
    }

    private static int compareRanges(List<RangeStatistics> r1,
                                     List<RangeStatistics> r2)
    {
        if (r1.isEmpty()) {
            if (r2.isEmpty()) {
                return 0;
            } else {
                return -1;
            }
        } else if (r2.isEmpty()) {
            return 1;
        }
        Double v1 = r1.get(0).getValue();
        Double v2 = r2.get(0).getValue();
        if (v1 == null) {
            if (v2 == null) {
                return 0;
            } else {
                return -1;
            }
        } else if (v2 == null) {
            return 1;
        }
        return v1.compareTo(v2);
    }
}
