package ru.yandex.qe.dispenser.client.v1.impl;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import javax.ws.rs.core.GenericType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.yandex.qe.dispenser.api.v1.DiQuota;
import ru.yandex.qe.dispenser.api.v1.response.DiListPageResponse;
import ru.yandex.qe.dispenser.api.v1.response.DiQuotaGetResponse;

final class GetFullQuotasRequestBuilderImpl extends GetQuotasRequestBuilderBase<DiQuotaGetResponse> {
    private static final Logger LOG = LoggerFactory.getLogger(GetFullQuotasRequestBuilderImpl.class);
    public static final GenericType<DiListPageResponse<DiQuota>> PAGE_TYPE = new GenericType<DiListPageResponse<DiQuota>>() {
    };

    GetFullQuotasRequestBuilderImpl(final @NotNull Supplier<WebClient> clients) {
        super(clients);
    }

    @NotNull
    @Override
    protected DiQuotaGetResponse perform(@NotNull final WebClient filteredClient) {
        final WebClient client = filteredClient.replacePath("/v3/quotas");

        final DiListPageItemIterator<DiQuota> iterator = new DiListPageItemIterator<>(client, PAGE_TYPE);

        final List<DiQuota> quotas = iterator.stream().collect(Collectors.toList());

        final DiQuotaGetResponse response = new DiQuotaGetResponse(quotas);

        if (LOG.isDebugEnabled()) {
            response.stream()
                    .filter(q -> q.getActual().getValue() >= q.getMax().getValue())
                    .forEach(q -> LOG.debug("Overquoting detected! {}", q));
        }

        return response;
    }
}
