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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据源方法
 */
public class DatabaseUtil {


    public static List<String> loadDatabaseTables(DataSourceInfo dataSourceInfo) {


        List<String> tables = new ArrayList<>();

        String sql = "show tables";

        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");

        if (!"dataSource".equals(dataSourceInfo.getCode())) {
            if ("Mysql".equals(dataSourceInfo.getDatabaseType())) {
                url = "jdbc:mysql://" + dataSourceInfo.getUrl() + "/" + dataSourceInfo.getDatabaseName();
                user = dataSourceInfo.getUsername();
                password = dataSourceInfo.getPassword();
            } else if ("SqlServer".equals(dataSourceInfo.getDatabaseType())) {
                DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                url = "jdbc:sqlserver://" + dataSourceInfo.getUrl() + ";DatabaseName=" + dataSourceInfo.getDatabaseName();
                user = dataSourceInfo.getUsername();
                password = dataSourceInfo.getPassword();
                sql = "select * from sys.tables order by name";
            }

        }


        Connection conn = JDBC.connectDB(DRIVER, url, user, password);
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {

                tables.add(rs.getString(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return tables;
    }


}
