package com.gyee.wisdom.dao.taoscz;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;


@Slf4j
@Configuration
public class TaosConfiguration {

    @Value("${taos.server_ip:127.0.0.1}")
    private String serverIp;

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

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

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

    @Value("${taos.pool_size:50}")
    private int poolSize;

    @Value("${taos.max_pool_size:200}")
    private int maxPoolSize;

    private DataSource dataSource;

    private String dbname = "gdnxxny";


    public Connection getConnect() {
        try {
            if (null == dataSource) {
                dataSource = getDataSource();
            }
            return dataSource.getConnection();

        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return null;
    }

    private DataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        // jdbc properties
        String url = "jdbc:TAOS-RS://" + serverIp + ":" + serverPort + "/gdnxxny";
        dataSource.setDriverClassName("com.taosdata.jdbc.rs.RestfulDriver");
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        // pool configurations
        dataSource.setInitialSize(poolSize);
        dataSource.setMinIdle(poolSize);
        dataSource.setMaxActive(maxPoolSize);
        dataSource.setMaxWait(300000);
        dataSource.setRemoveAbandoned(true);
        dataSource.setLogAbandoned(true);
        dataSource.setRemoveAbandonedTimeoutMillis(300000);
        dataSource.setValidationQuery("select server_status()");

        log.info("涛思数据源初始化成功……");

        return dataSource;
    }

    public void close(Connection conn, Statement st, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (st != null) st.close();
            if (conn != null) conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}