package be.iminds.ilabt.jfed.lowlevel.connection;

import be.iminds.ilabt.jfed.lowlevel.JFedException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * BasicHttpConnection
 */
public class BasicHttpConnection extends HttpConnection {
    private static final Logger LOG = LoggerFactory.getLogger(BasicHttpConnection.class);

    private final HttpClientBuilder clientBuilder;
    private final HttpContext httpContext;
    private final HttpContext preemptiveAuthHttpContext;

    private CloseableHttpClient httpClient;

    private boolean preemptiveAuthEnabled = false;

    public BasicHttpConnection(ConnectionConfig connectionConfig,
                               HttpClientBuilder clientBuilder, HttpContext httpContext, HttpContext preemptiveAuthHttpContext) throws JFedException {
        super(connectionConfig);
        this.clientBuilder = clientBuilder;
        this.httpContext = httpContext;
        this.preemptiveAuthHttpContext = preemptiveAuthHttpContext;
    }

    @Override
    public void enablePreemptiveAuthentication(boolean enable) {
        preemptiveAuthEnabled = enable;
    }

    @Override
    public CloseableHttpClient getHttpClient() {

        if (httpClient == null)
            httpClient = clientBuilder.build();

        return httpClient;
    }

    @Override
    public HttpContext getHttpContext() {
        if (preemptiveAuthEnabled)
            return preemptiveAuthHttpContext;
        else
            return httpContext;
    }

    @Override
    public void close() {
        error = true;
        try {
            httpClient.close();
        } catch (IOException e) {
            LOG.warn("Error while closing http client");
        }
        httpClient = null;
    }
}

