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

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.stream.Collectors;

import lombok.Setter;
import org.jetbrains.annotations.NotNull;

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

/**
 * @author aherman
 */
public class QueryStatisticsFiltersService {

    @Setter
    private String allRegionsFilter;

    @NotNull
    public String getRegionFilter(RegionInclusion regionInclusion, Integer[] regionIds) {
        return getRegionFilter(regionInclusion,
                regionIds == null ? Collections.emptyList() :
                        Arrays.stream(regionIds).filter(Objects::nonNull).collect(Collectors.toList()));
    }

    @NotNull
    public String getRegionFilter(RegionInclusion regionInclusion, Collection<Integer> regionIds) {
        if (regionIds.isEmpty()) {
            return allRegionsFilter;
        }

        String regionFilter = regionIds.stream()
                .map(r -> "regionIn(toUInt32(region_id), toUInt32(" + r + "))")
                .collect(Collectors.joining(" OR "));

        if (regionInclusion == RegionInclusion.INCLUDE_ALL) {
            regionFilter = "(" + regionFilter + ")";
        } else {
            regionFilter = "NOT (" + regionFilter + ")";
        }
        return regionFilter;
    }

}
