package com.zcloud.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.Data;
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.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
@Data
public class ElasticsearchConfiguration {
    private String host;
    private int port;
    private String username;
    private String password;

    /**
     * 解析配置的字符串，转为HttpHost对象数组
     *
     * @return
     */
    private HttpHost toHttpHost() {
        HttpHost httpHost = new HttpHost(host, port, "http");
        return httpHost;
    }

    /**
     * 同步客户端
     *
     * @return
     * @throws Exception
     */
    @Bean
    public ElasticsearchClient clientBySync() throws Exception {
        ElasticsearchTransport transport = getElasticsearchTransport(username, password, toHttpHost());
        return new ElasticsearchClient(transport);
    }

    /**
     * 异步客户端
     *
     * @return
     * @throws Exception
     */
    @Bean
    public ElasticsearchAsyncClient clientByAsync() throws Exception {
        ElasticsearchTransport transport = getElasticsearchTransport(username, password, toHttpHost());
        return new ElasticsearchAsyncClient(transport);
    }

    /**
     * 传输对象
     *
     * @return
     * @throws Exception
     */
    @Bean
    public ElasticsearchTransport getTransport() throws Exception {
        return getElasticsearchTransport(username, password, toHttpHost());
    }


    private static ElasticsearchTransport getElasticsearchTransport(String username, String passwd, HttpHost... hosts) {
        // 账号密码的配置
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, passwd));

        RestClientBuilder.HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
                .setDefaultCredentialsProvider(credentialsProvider);

        // 用builder创建RestClient对象
        RestClient client = RestClient
                .builder(hosts)
                .setHttpClientConfigCallback(callback)
                .build();
        return new RestClientTransport(client, new JacksonJsonpMapper());
    }


}
