package ru.yandex.webmaster3.storage.http.searchquery.statistic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.searchquery.PathId;
import ru.yandex.webmaster3.core.searchquery.QueryGroupId;
import ru.yandex.webmaster3.core.searchquery.QueryId;

/**
 * @author aherman
 */
public class StatisticsHelper {
    public static <T> List<T> asList(int limit, T... value) {
        if (value == null || value.length == 0) {
            return Collections.emptyList();
        }
        ArrayList<T> result = new ArrayList<T>();
        for (T t : value) {
            if (t != null) {
                result.add(t);
                if (result.size() >= limit) {
                    break;
                }
            }
        }
        return result;
    }

    public static <T> Set<T> asSet(int limit, T... value) {
        if (value == null || value.length == 0) {
            return Collections.emptySet();
        }
        Set<T> result = new HashSet<>();
        for (T t : value) {
            if (t != null) {
                result.add(t);
                if (result.size() >= limit) {
                    break;
                }
            }
        }
        return result;
    }

    public static List<QueryGroupId> asGroupIds(int limit, WebmasterHostId hostId, String... value) {
        return asList(limit, value).stream()
                .map(s -> QueryGroupId.byGroupIdStr(hostId, s))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    public static List<QueryId> asQueryIds(int limit, String... value) {
        return asList(limit, value).stream()
                .map(QueryId::fromStringId)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    public static List<PathId> asPathIds(int limit, String... value) {
        return asList(limit, value).stream()
                .map(PathId::fromStringId)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }
}
