package com.yeejoin.equipmanage.config;

import org.apache.commons.lang3.StringUtils;
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.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {
 
	@Value("${spring.elasticsearch.rest.uris}")
    private String uris;

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

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

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

			try {
        	String url = uris.replace("http://", "");
        	final String[] parts = StringUtils.split(url, ":");
        	HttpHost httpHost = new HttpHost(parts[0], Integer.parseInt(parts[1]), "http");
        	RestClientBuilder builder = RestClient.builder(httpHost);
        	builder.setHttpClientConfigCallback(httpClientBuilder -> {
				httpClientBuilder.disableAuthCaching();
				return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
			});

			builder.setRequestConfigCallback((requestConfigBuilder)->requestConfigBuilder.setConnectTimeout(5000 * 1000).setSocketTimeout(6000 * 1000));


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