package com.izouma.awesomeadmin.util;

import com.izouma.awesomeadmin.model.DataSourceInfo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源常量
 */
public class Const {

    /**
     * 数据源常量
     */
    public static Map<String, DataSourceInfo> DataSourceInfoMap = new HashMap<>();


    // 加载必要常量
    public void initData() {
        loadDataSourceInfo();
    }


    private void loadDataSourceInfo() {

        String DRIVER = "com.mysql.jdbc.Driver";

        //读取配置文件
        PropertiesFileLoader propertiesFileLoader = PropertiesFileLoader.getInstance();
        propertiesFileLoader.getProperties("properties/jdbc.properties", "jdbc.url");

        String url = propertiesFileLoader.getProperties("properties/jdbc.properties", "jdbc.url");
        String user = propertiesFileLoader.getProperties("properties/jdbc.properties", "jdbc.username");
        String password = propertiesFileLoader.getProperties("properties/jdbc.properties", "jdbc.password");

        //读取数据源表
        String sql = "SELECT * FROM sys_data_source_info WHERE del_flag = 'N'";

        Connection conn = JDBC.connectDB(DRIVER, url, user, password);
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                DataSourceInfo dataSourceInfo = new DataSourceInfo();
                dataSourceInfo.setId(rs.getInt(1));
                dataSourceInfo.setCode(rs.getString(3));
                dataSourceInfo.setDatabaseType(rs.getString(4));
                dataSourceInfo.setUrl(rs.getString(5));
                dataSourceInfo.setUsername(rs.getString(6));
                dataSourceInfo.setPassword(rs.getString(7));
                dataSourceInfo.setDatabaseName(rs.getString(8));

                //添加到常量中
                DataSourceInfoMap.put(rs.getString(3), dataSourceInfo);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
