package com.yeejoin.amos.patrol.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
public class ElasticSearchClientConfig {

    @Value("${spring.elasticsearch.rest.uris}")
    private String uris;
    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;

    @Value("${elasticsearch.maxConnectNum:1000}")
    private int maxConnectNum;

    @Value("${elasticsearch.maxConnectPerRoute:1000}")
    private int maxConnectPerRoute;


    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));

        try {
            HttpHost[] httpHosts = Arrays.stream(uris.split(",")).map(HttpHost::create).toArray(HttpHost[]::new);
            RestClientBuilder builder = RestClient.builder(httpHosts);
            builder.setHttpClientConfigCallback(httpClientBuilder -> {
                httpClientBuilder.disableAuthCaching();
                httpClientBuilder.setMaxConnTotal(maxConnectNum);
                httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            });
            // 该方法接收一个RequestConfig.Builder对象，对该对象进行修改后然后返回。
            builder.setRequestConfigCallback(requestConfigBuilder -> {
                // 连接超时（默认为1秒）
                return requestConfigBuilder.setConnectTimeout(5000 * 1000)
                        // 套接字超时（默认为30秒）//更改客户端的超时限制默认30秒现在改为100*1000分钟
                        .setSocketTimeout(6000 * 1000);
            });

            return new RestHighLevelClient(builder);
        } catch (Exception e) {
            throw new IllegalStateException("Invalid ES nodes " + "property '" + uris + "'", e);
        }
    }
}
