package com.iailab.module.data.influxdb.common.config;

import com.iailab.framework.tenant.core.context.TenantContextHolder;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author PanZhibao
 * @Description
 * @createTime 2023年04月25日 17:13:00
 */
@Component
public class InfluxDBInstance {

    @Value("${influx-db.org}")
    public String org;

    @Value("${influx-db.bucket}")
    public String bucket;

    @Value("${influx-db.token}")
    public String token;

    @Value("${influx-db.url}")
    public String url;

    private final static String BUCKET_NAME = "tenant_";

    private Logger logger = LoggerFactory.getLogger(getClass());

    private InfluxDBClient client;

    public InfluxDBClient getClient() {
        try {
            if (client == null) {
                client = InfluxDBClientFactory.create(url, token.toCharArray());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("创建InfluxDBClient失败!");
        }
        return client;
    }

    public String getBucket() {
        return BUCKET_NAME + TenantContextHolder.getRequiredTenantId();
    }

}