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

import java.util.Arrays;
import java.util.function.Supplier;

import javax.ws.rs.core.GenericType;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.apache.cxf.jaxrs.client.WebClient;
import org.jetbrains.annotations.NotNull;

import ru.yandex.qe.dispenser.client.QueryableRequestBuilder;

class QueryableRequestBuilderImpl<T> implements QueryableRequestBuilder<T> {
    @NotNull
    private final Multimap<String, String> params = HashMultimap.create();
    @NotNull
    private final Supplier<WebClient> clientProvider;
    private final @NotNull GenericType<T> returnType;

    QueryableRequestBuilderImpl(@NotNull final GenericType<T> returnType,
                                @NotNull final Supplier<WebClient> clientProvider) {
        this.clientProvider = clientProvider;
        this.returnType = returnType;
    }

    @Override
    @NotNull
    public QueryableRequestBuilder<T> query(final String key, final String... value) {
        params.putAll(key, Arrays.asList(value));
        return this;
    }

    @NotNull
    @Override
    public T perform() {
        final WebClient client = clientProvider.get();
        params.entries().forEach(e -> client.query(e.getKey(), e.getValue()));
        return client.get(returnType);
    }

}
