package cn.com.energy.config;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: wangpx
 * @date: 2025-07-03 10:50
 */
@Component
public class InfluxDBConfig {
    @Value("${influxdb.url}")
    private String url;

    @Value("${influxdb.token}")
    private String token;

    @Value("${influxdb.org}")
    private String org;

    // 使用 Map 存储不同 bucket 的 InfluxDBClient 实例，确保一个 bucket 只创建一个实例
    private static final Map<String, InfluxDBClient> clientPool = new ConcurrentHashMap<>();

    /**
     * 获取指定 bucket 的 InfluxDBClient，如果不存在则创建
     */
    public InfluxDBClient getClient(String bucket) {
        return clientPool.computeIfAbsent(bucket, b -> InfluxDBClientFactory.create(url, token.toCharArray(), org, b));
    }

    /**
     * 关闭指定 bucket 的客户端
     */
    public void closeClient(String bucket) {
        InfluxDBClient client = clientPool.remove(bucket);
        if (client != null) {
            client.close();
        }
    }

    /**
     * 关闭所有客户端
     */
    @PreDestroy
    public void closeAllClients() {
        clientPool.values().forEach(InfluxDBClient::close);
        clientPool.clear();
    }
}
