package ru.yandex.qe.http.telemetry;

import org.apache.http.impl.client.CloseableHttpClient;

import ru.yandex.monlib.metrics.registry.MetricRegistry;
import ru.yandex.qe.http.HttpClientBuilder;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Established by terry
 * on 02.01.14.
 */
public class MetricsInstrumentedHttpClientBuilder extends HttpClientBuilder {

    private final String label;
    private final MetricRegistry metricRegistry;

    public MetricsInstrumentedHttpClientBuilder(String label, MetricRegistry metricRegistry) {
        checkNotNull(label, "telemetry label must be specified");
        checkNotNull(metricRegistry, "telemetry metricRegistry must be specified");
        this.label = label;
        this.metricRegistry = metricRegistry;
        this.httpConnectionManagerBuilder =
                new InstrumentedHttpConnectionManagerBuilder(metricRegistry, label);
    }

    @Override
    public CloseableHttpClient build() {
        addRequestInterceptorFirst(new InstrumentedHttpRequestInterceptor(metricRegistry, label));
        addResponseInterceptorFirst(new InstrumentedHttpResponseInterceptor(metricRegistry, label));
        addAspectFactory(new MetricsTelemetryAspectFactory(metricRegistry, label));
        return super.build();
    }
}
