package ru.yandex.qe.dispenser.passport.blackbox;

import javax.annotation.Resource;

import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import ru.yandex.qe.dispenser.solomon.SolomonHolder;
import ru.yandex.qe.http.HttpClientBuilder;
import ru.yandex.qe.http.retries.RetryStrategy;
import ru.yandex.qe.http.telemetry.MetricsInstrumentedHttpClientBuilder;

/**
 * @author lvovich
 */
@Component
public class PassportHttpClientFactoryBean implements FactoryBean<CloseableHttpClient> {

    @Resource(name = "passportRetryStrategy")
    private RetryStrategy retryStrategy;

    @Value("${passport.telemetry.enabled:true}")
    private boolean telemetryEnabled;

    @Value("${plugin.passport.http.log.enable:false}")
    private boolean logEnabled;

    @Value("${plugin.passport.connect.timeout:1000}")
    private int connectTimeout;

    @Value("${plugin.passport.socket.timeout:5000}")
    private int socketTimeout;

    @Autowired
    private SolomonHolder solomonHolder;

    @Override
    public CloseableHttpClient getObject() {
        if (telemetryEnabled) {
            return new MetricsInstrumentedHttpClientBuilder("passport", solomonHolder.getRootRegistry())
                    .setRetryStrategy(retryStrategy)
                    .setLogEnable(logEnabled)
                    .setConnectTimeout(connectTimeout)
                    .setSocketTimeout(socketTimeout)
                    .build();
        } else {
            return new HttpClientBuilder()
                    .setRetryStrategy(retryStrategy)
                    .setLogEnable(logEnabled)
                    .setConnectTimeout(connectTimeout)
                    .setSocketTimeout(socketTimeout)
                    .build();
        }
    }

    @Override
    public Class<?> getObjectType() {
        return CloseableHttpClient.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
