package com.gyee.dataadapter.dao_mqtt_influxdb_taos;

import com.taosdata.jdbc.TSDBDriver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

@Slf4j
@Configuration
public class TaosConfig {

    @Value("${taoscz.server_ip:192.168.1.60}")
    private String serverIp;

    @Value("${taoscz.server_port:6030}")
    private int serverPort;

    @Value("${taoscz.db_name:js}")
    private String dbName;

    @Value("${taoscz.user_name:root}")
    private String userName;

    @Value("${taoscz.password:taosdata}")
    private String password;

    @Value("${taoscz.pool_size:10}")
    private int poolSize;

    @Value("${taoscz.max_pool_size:100}")
    private int maxPoolSize;

    @Value("${taoscz.driver_type:com.taosdata.jdbc.rs.RestfulDriver}")
    private String driverType;

    @Value("${taoscz.ai_stable_name:point_ci}")
    private String aiStableName;

    @Value("${taoscz.di_stable_name:point_di}")
    private String diStableName;

    private Connection connection = null;

    public Connection getInstance() throws ClassNotFoundException, SQLException {
        if (null == connection)
            connection = getConnection();

        return connection;
    }


    private Connection getConnection() throws ClassNotFoundException, SQLException {
        Connection connection = null;

        Class.forName(driverType);
        String jdbcUrl = "jdbc:TAOS-RS://" + serverIp + ":" + serverPort + "/" + dbName + "?user=" + userName + "&password=" + password;
        if (driverType.equals("com.taosdata.jdbc.TSDBDriver"))
            jdbcUrl = "jdbc:TAOS://" + serverIp + ":" + serverPort + "/" + dbName + "?user=" + userName + "&password=" + password;
        Properties connProps = new Properties();
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
        connection = DriverManager.getConnection(jdbcUrl, connProps);

        return connection;
    }

    public String getTableName(String tagName) {
        return dbName + "." + tagName.toLowerCase();
    }

    public String getDbName() {
        return dbName;
    }


    public String getAIStableName() {
        return aiStableName;
    }

    public String getDIStableName() {
        return diStableName;
    }
}