package org.xbib.io.webdav.client;

import java.net.Authenticator;
import java.net.CookieHandler;
import java.net.ProxySelector;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;

class WebDavHttpClientBuilder implements WebDavHttpClient.Builder {

    private final HttpClient.Builder builder = HttpClient.newBuilder();

    private final List<Consumer<HttpRequest.Builder>> decorators = new ArrayList<>();

    private final List<Interceptor<?>> interceptors = new ArrayList<>();

    @Override
    public WebDavHttpClient.Builder cookieHandler(CookieHandler cookieHandler) {
        builder.cookieHandler(cookieHandler);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder connectTimeout(Duration duration) {
        builder.connectTimeout(duration);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder sslContext(SSLContext sslContext) {
        builder.sslContext(sslContext);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder sslParameters(SSLParameters sslParameters) {
        builder.sslParameters(sslParameters);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder executor(Executor executor) {
        builder.executor(executor);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder followRedirects(HttpClient.Redirect redirect) {
        builder.followRedirects(redirect);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder version(HttpClient.Version version) {
        builder.version(version);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder priority(int priority) {
        builder.priority(priority);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder proxy(ProxySelector proxySelector) {
        builder.proxy(proxySelector);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder authenticator(Authenticator authenticator) {
        builder.authenticator(authenticator);
        return this;
    }

    @Override
    public WebDavHttpClient.Builder decorator(Consumer<HttpRequest.Builder> decorator) {
        Objects.requireNonNull(decorator, "decorator");
        decorators.add(decorator);
        return this;
    }

    @Override
    public <T> WebDavHttpClient.Builder interceptor(Interceptor<T> interceptor) {
        interceptors.add(interceptor);
        return this;
    }

    @Override
    public HttpClient build() {
        return new WebDavHttpClient(builder.build(), new ArrayList<>(decorators), new ArrayList<>(interceptors));
    }
}
