package com.artfess.es.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.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Configuration
@EnableConfigurationProperties({ElasticsearchConfig.class})
public class ElasticsearchRestHighClient {

    @Autowired
    ElasticsearchConfig elasticsearchConfig;

    @Bean
    public RestClientBuilder restClientBuilder() {
        HttpHost[] httpHosts = makeHttpHost(elasticsearchConfig.getHost());
        RestClientBuilder  restClientBuilder = RestClient.builder(httpHosts);
        String username = elasticsearchConfig.getUserName();
        if(!StringUtils.isEmpty(username) ){
            String password = elasticsearchConfig.getPassword();
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));

            restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
                httpClientBuilder.disableAuthCaching();
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            });

        }
        return restClientBuilder;
    }


    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient highLevelClient(RestClientBuilder restClientBuilder) {

        return new RestHighLevelClient(restClientBuilder);
    }


    private HttpHost[] makeHttpHost(String s) {
        HttpHost[] httpHosts = new HttpHost[]{};
        List<HttpHost> hostList = new ArrayList<>();
        String[] address = s.split(",");
        String ip;
        int port;
        for (String address1 : address) {
            String temp = address1.trim();
            String[] ipAndPort = temp.split(":");
            if (ipAndPort.length != 2) {
                continue;
            }
            ip = ipAndPort[0];
            port = Integer.parseInt(ipAndPort[1]);
            hostList.add(new HttpHost(ip, port, "http"));
        }
        return hostList.toArray(httpHosts);
    }
}
