package kr.gmtc.gw.elastic.config;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
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.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

@Configuration
//@EnableElasticsearchRepositories(basePackages = "kr.gmtc.gw.elk.repositories")
@ComponentScan(basePackages = {"kr.gmtc.gw.elk"})
public class ElasticsearchClientConfig extends AbstractElasticsearchConfiguration {

    @Value("${app.config.elastic.host}")
    private String gsEsHost;

    @Value("${app.config.elastic.port}")
    private int gsEsPort;

    // @Override
    // @Bean(destroyMethod = "close")
    // public RestHighLevelClient elasticsearchClient() {
    //     final ClientConfiguration clientConfiguration =
    //             ClientConfiguration
    //                     .builder()
    //                      .connectedTo(gsEsHost + ":" + gsEsPort)
    //                     //.connectedTo( "10.200.31.129:9200")
    //                     .build();

    //     return RestClients.create(clientConfiguration).rest();
    // }

    @Override
    @Bean(destroyMethod = "close")
    public RestHighLevelClient elasticsearchClient() {

        RestClientBuilder builder = RestClient.builder(
                new HttpHost(gsEsHost, gsEsPort))
                .setRequestConfigCallback(
                        new RestClientBuilder.RequestConfigCallback() {
                            @Override
                            public RequestConfig.Builder customizeRequestConfig(
                                    RequestConfig.Builder requestConfigBuilder) {
                                return requestConfigBuilder
                                        .setConnectTimeout(5000)
                                        .setSocketTimeout(60000);
                            }
                        });

        return new RestHighLevelClient(builder);
    }

    @Bean
    public ElasticsearchOperations esTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }
    
}
