/*
 * Copyright 2012-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.http.client;

import java.net.http.HttpClient;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.TlsSocketStrategy;
import org.apache.hc.core5.http.io.SocketConfig;
import org.jspecify.annotations.Nullable;

import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.boot.ssl.SslBundle;
import org.springframework.util.Assert;

/**
 * Builder that can be used to create a
 * <a href="https://hc.apache.org/httpcomponents-client-ga/">Apache HttpComponents</a>
 * {@link HttpClient}.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @author Scott Frederick
 * @since 3.5.0
 */
public final class HttpComponentsHttpClientBuilder {

	private final Consumer<HttpClientBuilder> customizer;

	private final Consumer<PoolingHttpClientConnectionManagerBuilder> connectionManagerCustomizer;

	private final Consumer<SocketConfig.Builder> socketConfigCustomizer;

	private final Consumer<ConnectionConfig.Builder> connectionConfigCustomizer;

	private final Consumer<RequestConfig.Builder> defaultRequestConfigCustomizer;

	private final TlsSocketStrategyFactory tlsSocketStrategyFactory;

	private final DnsResolver dnsResolver;

	public HttpComponentsHttpClientBuilder() {
		this(Empty.consumer(), Empty.consumer(), Empty.consumer(), Empty.consumer(), Empty.consumer(),
				HttpComponentsSslBundleTlsStrategy::get, SystemDefaultDnsResolver.INSTANCE);
	}

	private HttpComponentsHttpClientBuilder(Consumer<HttpClientBuilder> customizer,
			Consumer<PoolingHttpClientConnectionManagerBuilder> connectionManagerCustomizer,
			Consumer<SocketConfig.Builder> socketConfigCustomizer,
			Consumer<ConnectionConfig.Builder> connectionConfigCustomizer,
			Consumer<RequestConfig.Builder> defaultRequestConfigCustomizer,
			TlsSocketStrategyFactory tlsSocketStrategyFactory, DnsResolver dnsResolver) {
		this.customizer = customizer;
		this.connectionManagerCustomizer = connectionManagerCustomizer;
		this.socketConfigCustomizer = socketConfigCustomizer;
		this.connectionConfigCustomizer = connectionConfigCustomizer;
		this.defaultRequestConfigCustomizer = defaultRequestConfigCustomizer;
		this.tlsSocketStrategyFactory = tlsSocketStrategyFactory;
		this.dnsResolver = dnsResolver;
	}

	/**
	 * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional
	 * customization to the underlying {@link HttpClientBuilder}.
	 * @param customizer the customizer to apply
	 * @return a new {@link HttpComponentsHttpClientBuilder} instance
	 */
	public HttpComponentsHttpClientBuilder withCustomizer(Consumer<HttpClientBuilder> customizer) {
		Assert.notNull(customizer, "'customizer' must not be null");
		return new HttpComponentsHttpClientBuilder(this.customizer.andThen(customizer),
				this.connectionManagerCustomizer, this.socketConfigCustomizer, this.connectionConfigCustomizer,
				this.defaultRequestConfigCustomizer, this.tlsSocketStrategyFactory, this.dnsResolver);
	}

	/**
	 * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional
	 * customization to the underlying {@link PoolingHttpClientConnectionManagerBuilder}.
	 * @param connectionManagerCustomizer the customizer to apply
	 * @return a new {@link HttpComponentsHttpClientBuilder} instance
	 */
	public HttpComponentsHttpClientBuilder withConnectionManagerCustomizer(
			Consumer<PoolingHttpClientConnectionManagerBuilder> connectionManagerCustomizer) {
		Assert.notNull(connectionManagerCustomizer, "'connectionManagerCustomizer' must not be null");
		return new HttpComponentsHttpClientBuilder(this.customizer,
				this.connectionManagerCustomizer.andThen(connectionManagerCustomizer), this.socketConfigCustomizer,
				this.connectionConfigCustomizer, this.defaultRequestConfigCustomizer, this.tlsSocketStrategyFactory,
				this.dnsResolver);
	}

	/**
	 * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional
	 * customization to the underlying
	 * {@link org.apache.hc.core5.http.io.SocketConfig.Builder}.
	 * @param socketConfigCustomizer the customizer to apply
	 * @return a new {@link HttpComponentsHttpClientBuilder} instance
	 */
	public HttpComponentsHttpClientBuilder withSocketConfigCustomizer(
			Consumer<SocketConfig.Builder> socketConfigCustomizer) {
		Assert.notNull(socketConfigCustomizer, "'socketConfigCustomizer' must not be null");
		return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer,
				this.socketConfigCustomizer.andThen(socketConfigCustomizer), this.connectionConfigCustomizer,
				this.defaultRequestConfigCustomizer, this.tlsSocketStrategyFactory, this.dnsResolver);
	}

	/**
	 * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional
	 * customization to the underlying
	 * {@link org.apache.hc.client5.http.config.ConnectionConfig.Builder}.
	 * @param connectionConfigCustomizer the customizer to apply
	 * @return a new {@link HttpComponentsHttpClientBuilder} instance
	 */
	public HttpComponentsHttpClientBuilder withConnectionConfigCustomizer(
			Consumer<ConnectionConfig.Builder> connectionConfigCustomizer) {
		Assert.notNull(connectionConfigCustomizer, "'connectionConfigCustomizer' must not be null");
		return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer,
				this.socketConfigCustomizer, this.connectionConfigCustomizer.andThen(connectionConfigCustomizer),
				this.defaultRequestConfigCustomizer, this.tlsSocketStrategyFactory, this.dnsResolver);
	}

	/**
	 * Return a new {@link HttpComponentsHttpClientBuilder} with a replacement
	 * {@link TlsSocketStrategy} factory.
	 * @param tlsSocketStrategyFactory the new factory used to create a
	 * {@link TlsSocketStrategy}. The function will be provided with a {@link SslBundle}
	 * or {@code null} if no bundle is selected. Only non {@code null} results will be
	 * applied.
	 * @return a new {@link HttpComponentsHttpClientBuilder} instance
	 */
	public HttpComponentsHttpClientBuilder withTlsSocketStrategyFactory(
			TlsSocketStrategyFactory tlsSocketStrategyFactory) {
		Assert.notNull(tlsSocketStrategyFactory, "'tlsSocketStrategyFactory' must not be null");
		return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer,
				this.socketConfigCustomizer, this.connectionConfigCustomizer, this.defaultRequestConfigCustomizer,
				tlsSocketStrategyFactory, this.dnsResolver);
	}

	/**
	 * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional
	 * customization to the underlying
	 * {@link org.apache.hc.client5.http.config.RequestConfig.Builder} used for default
	 * requests.
	 * @param defaultRequestConfigCustomizer the customizer to apply
	 * @return a new {@link HttpComponentsHttpClientBuilder} instance
	 */
	public HttpComponentsHttpClientBuilder withDefaultRequestConfigCustomizer(
			Consumer<RequestConfig.Builder> defaultRequestConfigCustomizer) {
		Assert.notNull(defaultRequestConfigCustomizer, "'defaultRequestConfigCustomizer' must not be null");
		return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer,
				this.socketConfigCustomizer, this.connectionConfigCustomizer,
				this.defaultRequestConfigCustomizer.andThen(defaultRequestConfigCustomizer),
				this.tlsSocketStrategyFactory, this.dnsResolver);
	}

	/**
	 * Return a new {@link HttpComponentsHttpClientBuilder} with a replacement
	 * {@link DnsResolver}.
	 * @param dnsResolver the new DNS resolver
	 * @return a new {@link HttpComponentsHttpClientBuilder} instance
	 * @since 4.1.0
	 */
	public HttpComponentsHttpClientBuilder withDnsResolver(DnsResolver dnsResolver) {
		Assert.notNull(dnsResolver, "'dnsResolver' must not be null");
		return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer,
				this.socketConfigCustomizer, this.connectionConfigCustomizer, this.defaultRequestConfigCustomizer,
				this.tlsSocketStrategyFactory, dnsResolver);
	}

	/**
	 * Build a new {@link HttpClient} instance with the given settings applied.
	 * @param settings the settings to apply
	 * @return a new {@link HttpClient} instance
	 */
	public CloseableHttpClient build(@Nullable HttpClientSettings settings) {
		settings = (settings != null) ? settings : HttpClientSettings.defaults();
		HttpClientBuilder builder = HttpClientBuilder.create()
			.useSystemProperties()
			.setRedirectStrategy(HttpComponentsRedirectStrategy.get(settings.redirects()))
			.setConnectionManager(createConnectionManager(settings))
			.setDefaultRequestConfig(createDefaultRequestConfig(settings));
		this.customizer.accept(builder);
		return builder.build();
	}

	private PoolingHttpClientConnectionManager createConnectionManager(HttpClientSettings settings) {
		PoolingHttpClientConnectionManagerBuilder builder = PoolingHttpClientConnectionManagerBuilder.create()
			.useSystemProperties();
		PropertyMapper map = PropertyMapper.get();
		builder.setDefaultSocketConfig(createSocketConfig());
		builder.setDefaultConnectionConfig(createConnectionConfig(settings));
		map.from(settings::sslBundle)
			.always()
			.as(this.tlsSocketStrategyFactory::getTlsSocketStrategy)
			.to(builder::setTlsSocketStrategy);
		DnsResolver dnsResolver = this.dnsResolver;
		if (settings.inetAddressFilter() != null) {
			dnsResolver = new HttpComponentsFilteredDnsResolver(dnsResolver, settings.inetAddressFilter());
		}
		builder.setDnsResolver(dnsResolver);
		this.connectionManagerCustomizer.accept(builder);
		return builder.build();
	}

	private SocketConfig createSocketConfig() {
		SocketConfig.Builder builder = SocketConfig.custom();
		this.socketConfigCustomizer.accept(builder);
		return builder.build();
	}

	private ConnectionConfig createConnectionConfig(HttpClientSettings settings) {
		ConnectionConfig.Builder builder = ConnectionConfig.custom();
		PropertyMapper map = PropertyMapper.get();
		map.from(settings::connectTimeout)
			.as(Duration::toMillis)
			.to((timeout) -> builder.setConnectTimeout(timeout, TimeUnit.MILLISECONDS));
		map.from(settings::readTimeout)
			.asInt(Duration::toMillis)
			.to((timeout) -> builder.setSocketTimeout(timeout, TimeUnit.MILLISECONDS));
		this.connectionConfigCustomizer.accept(builder);
		return builder.build();
	}

	private RequestConfig createDefaultRequestConfig(HttpClientSettings settings) {
		RequestConfig.Builder builder = RequestConfig.custom();
		if (settings.cookieHandling() != null) {
			String cookieSpec = switch (settings.cookieHandling()) {
				case ENABLE_WHEN_POSSIBLE, ENABLE -> StandardCookieSpec.STRICT;
				case DISABLE -> StandardCookieSpec.IGNORE;
			};
			builder.setCookieSpec(cookieSpec);
		}
		this.defaultRequestConfigCustomizer.accept(builder);
		return builder.build();
	}

	/**
	 * Factory that can be used to optionally create a {@link TlsSocketStrategy} given an
	 * {@link SslBundle}.
	 *
	 * @since 4.0.0
	 */
	public interface TlsSocketStrategyFactory {

		/**
		 * Return the {@link TlsSocketStrategy} to use for the given bundle.
		 * @param sslBundle the SSL bundle or {@code null}
		 * @return the {@link TlsSocketStrategy} to use or {@code null}
		 */
		@Nullable TlsSocketStrategy getTlsSocketStrategy(@Nullable SslBundle sslBundle);

	}

}
