package cn.ibizlab.core.data.elasticsearch;

import cn.ibizlab.core.data.model.DSLink;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.client.reactive.ReactiveRestClients;
import org.springframework.http.HttpHeaders;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class DynamicEsContextHolder
{

  public static final Map<String, ReactiveElasticsearchClient> ES_CLIENT_DB_FACTORY_MAP = new HashMap<>();
  public static final ThreadLocal<ReactiveElasticsearchClient> ES_DB_FACTORY_THREAD_LOCAL =
      new ThreadLocal<>();

  public static ReactiveElasticsearchClient getReactiveElasticsearchClient() {
    return ES_DB_FACTORY_THREAD_LOCAL.get();
  }

  public static void push(String name) {
    ES_DB_FACTORY_THREAD_LOCAL.set(ES_CLIENT_DB_FACTORY_MAP.get(name));
  }

  public static void poll() {
    ES_DB_FACTORY_THREAD_LOCAL.remove();
  }

  public static synchronized void addFactory(String ds, DSLink link)
  {
    addFactory(ds,link.getUrl());
  }

  public static synchronized void addFactory(String ds, String uri)
  {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("some-header", "on every request");

    HttpHeaders headers=new HttpHeaders();
    headers.add("currentTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

    ClientConfiguration clientConfiguration = ClientConfiguration.builder()
            .connectedTo("localhost:9200"/*, "localhost:9291"*/)
            //.useSsl()
            //.withProxy("localhost:8888")
            //.withPathPrefix("ela")
            .withConnectTimeout(Duration.ofSeconds(5))
            .withSocketTimeout(Duration.ofSeconds(3))
            //.withDefaultHeaders(defaultHeaders)
            //.withBasicAuth(username, password)
            .withDefaultHeaders(headers)
            .build();
    ES_CLIENT_DB_FACTORY_MAP.put(ds, ReactiveRestClients.create(clientConfiguration));
  }

  public static synchronized void removeFactory(String ds)
  {
    ES_CLIENT_DB_FACTORY_MAP.remove(ds);
  }



}
