package com.zm.order.tool.server.config;

import com.google.common.base.Throwables;
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.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;

/**
 * @Description 搜索配置类
 * @Author: ph
 * @Date: 2019/10/30 10:37
 */
@Configuration
@EnableConfigurationProperties(EsProperty.class)
public class EsConfig implements ApplicationListener<ContextClosedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(EsConfig.class);

    private RestHighLevelClient esClient;

    @Bean
    public RestHighLevelClient esClient(@Autowired EsProperty esProperty) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(esProperty.getUserName(), esProperty.getPassword()));
        esClient = new RestHighLevelClient(RestClient.builder(new HttpHost(esProperty.getHost(), esProperty.getPort()))
                .setRequestConfigCallback(
                        requestConfigBuilder -> requestConfigBuilder
                                .setConnectTimeout(esProperty.getConnectionTimeout())
                                .setSocketTimeout(esProperty.getSocketTimeout()))
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)));
        logger.info("init es client success");
        return esClient;
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        if (esClient != null) {
            try {
                esClient.close();
                logger.info("close es client success");
            } catch (Throwable throwable) {
                logger.error("EsConfig[onApplicationEvent] failed, cause by:",
                        Throwables.getStackTraceAsString(throwable));
            }
        }
    }
}
