package com.yaohun.mcbot.data.sql;

import com.yaohun.mcbot.config.Config;

import java.sql.*;

public class SQLIO {

    private static String host;
    private static int port;
    private static String database;
    private static String username;
    private static String password;
    private static String tableName;

    private static Connection connection;

    public static void init(){
        host = Config.SQL_Host;
        port = Integer.parseInt(Config.SQL_Port);
        database = Config.SQL_Database;
        username = Config.SQL_Users;
        password = Config.SQL_Password;
        tableName = "binddata";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            getConnection();
            initTable();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void initTable() {
        try {
            Statement stat = getConnection().createStatement();
            stat.execute(
                    "CREATE TABLE IF NOT EXISTS "+tableName+" (" +
                            "    username       VARCHAR(64) NOT NULL," +
                            "    userid  VARCHAR(64) NOT NULL," +
                            "    PRIMARY KEY (username)" +
                            ")"
            );
            stat.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static boolean hasUserNameExit(String userName) {
        try {
            try (PreparedStatement ps = getConnection().prepareStatement("SELECT `userid` FROM "+tableName+" WHERE `username` = ? LIMIT 1")) {
                ps.setString(1, userName);
                try (ResultSet rs = ps.executeQuery()) {
                    return rs.next();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean hasUserIDExit(String userID) {
        try {
            String sql = "SELECT `username` FROM " + tableName + " WHERE `userid` = ? LIMIT 1";
            try (PreparedStatement ps = getConnection().prepareStatement(sql)) {
                ps.setString(1, userID);
                try (ResultSet rs = ps.executeQuery()) {
                    return rs.next(); // 查询到了，说明存在
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void saveGroup(String userName, String userID) {
        if (!SQLIO.hasUserNameExit(userName)) {
            insertGroup(userName, userID);
        } else {
            updateGroup(userName, userID);
        }
    }

    private static void insertGroup(String userName, String userID) {
        try {
            String sql = "INSERT INTO "+tableName+"(username, userid) VALUES(?,?);";
            try (PreparedStatement ps = SQLIO.getConnection().prepareStatement(sql)) {
                ps.setString(1, userName);
                ps.setString(2 , userID);
                ps.executeUpdate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void updateGroup(String userName, String userID) {
        try {
            String sql = "UPDATE `"+tableName+"` SET `userid` = ? WHERE `username` = ? LIMIT 1";
            try (PreparedStatement ps = SQLIO.getConnection().prepareStatement(sql)) {
                ps.setString(1, userID);
                ps.setString(2, userName);
                ps.executeUpdate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getUserID(String userName) {
        try {
            String sql = "SELECT `userid` FROM `"+tableName+"` WHERE `username` = ? LIMIT 1";
            try (PreparedStatement ps = SQLIO.getConnection().prepareStatement(sql)) {
                ps.setString(1, userName);
                try (ResultSet resultSet = ps.executeQuery()) {
                    if (resultSet.next()) {
                        return resultSet.getString(1);
                    }
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUserName(String userID) {
        try {
            String sql = "SELECT `username` FROM `" + tableName + "` WHERE `userid` = ? LIMIT 1";
            try (PreparedStatement ps = SQLIO.getConnection().prepareStatement(sql)) {
                ps.setString(1, userID);
                try (ResultSet resultSet = ps.executeQuery()) {
                    if (resultSet.next()) {
                        return resultSet.getString(1);  // 返回 username
                    }
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Connection getConnection() {
        try {
            if (connection == null) {
                String url = "jdbc:mysql://" + host + ":" + port + "/" + database
                        + "?autoReconnect=true"
                        + "&failOverReadOnly=false"
                        + "&allowMultiQueries=true"
                        + "&useSSL=false"
                        + "&useUnicode=true"
                        + "&characterEncoding=utf8";
                connection = DriverManager.getConnection(url, username, password);
                System.out.println("[AuBot] 数据库: "+host+":"+port+"/"+database+"   (已正常连接)");
                return connection;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[AuBot] 数据库: "+host+":"+port+"/"+database+"   (连接失败)");
        }
        return connection;
    }

    public static void closeConnection() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
