package ru.yandex.qe.http;

import java.util.concurrent.TimeUnit;

import org.apache.http.config.Registry;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 * Established by terry on 16.03.14.
 */
public class HttpConnectionManagerBuilder {

    private long ttl = -1;
    private TimeUnit ttlTimeUnit = TimeUnit.MILLISECONDS;

    private int maxTotal = 20;
    private int maxPerRoute = maxTotal;
    private Registry<ConnectionSocketFactory> connectionSocketFactoryRegistry;
    private int socketTimeout = 30000;

    public HttpConnectionManagerBuilder setPooledConnectionTTL(long ttl, TimeUnit ttlTimeUnit) {
        this.ttl = ttl;
        this.ttlTimeUnit = ttlTimeUnit;
        return this;
    }

    public HttpConnectionManagerBuilder setConnectionPoolSize(int maxTotal) {
        this.maxTotal = maxTotal;
        return this;
    }

    public HttpConnectionManagerBuilder setPerRouteConcurrentLimit(int maxPerRoute) {
        this.maxPerRoute = maxPerRoute;
        return this;
    }

    public HttpConnectionManagerBuilder setConnectionSocketFactoryRegistry(Registry<ConnectionSocketFactory> connectionSocketFactoryRegistry) {
        this.connectionSocketFactoryRegistry = connectionSocketFactoryRegistry;
        return this;
    }

    public void setSocketTimeout(final int socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public HttpClientConnectionManager build() {
        PoolingHttpClientConnectionManager connectionManager;
        if (connectionSocketFactoryRegistry == null) {
            connectionManager = new PoolingHttpClientConnectionManager(ttl, ttlTimeUnit);
        } else {
            connectionManager = new PoolingHttpClientConnectionManager(connectionSocketFactoryRegistry, null, null, null, ttl, ttlTimeUnit);
        }
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(maxPerRoute);
        // enable staling connection - org.apache.http.client.config.RequestConfig#isStaleConnectionCheckEnabled()
        connectionManager.setValidateAfterInactivity(1);
        connectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
        return connectionManager;
    }

}
