package net.lax1dude.eaglercraft.v1_8.plugin.gateway_bungeecord.command;

import net.lax1dude.eaglercraft.v1_8.plugin.gateway_bungeecord.EaglerXBungee;
import net.lax1dude.eaglercraft.v1_8.plugin.gateway_bungeecord.auth.DefaultAuthSystem;
import net.lax1dude.eaglercraft.v1_8.plugin.gateway_bungeecord.server.EaglerInitialHandler;
import net.lax1dude.eaglercraft.v1_8.plugin.gateway_bungeecord.sqlite.EaglerDrivers;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;

import java.sql.*;
import java.util.Properties;

public class CommandBan extends Command {
    public CommandBan() {
        super("bban", "eaglercraft.command.ban");
    }

    @Override
    public void execute(CommandSender var1, String[] var2) {
        if (var2.length < 1) {
            var1.sendMessage(new TextComponent(ChatColor.RED + "How to use: " + ChatColor.WHITE + "/bungeeban <player> (reason)"));
        } else {
            ProxiedPlayer player = ProxyServer.getInstance().getPlayer(var2[0]);
            boolean isOnline = player != null;
            if (isOnline) {
                PendingConnection conn1 = player.getPendingConnection();
                if (!(conn1 instanceof EaglerInitialHandler)) {
                    var1.sendMessage(new TextComponent(ChatColor.RED + "That user is not using Eaglercraft"));
                    return;
                }
            }
            String databaseURI = EaglerXBungee.getEagler().getConfig().getBanURI();
            Connection conn;
            try {
                conn = EaglerDrivers.connectToDatabase(databaseURI,
                        EaglerXBungee.getEagler().getConfig().getAuthConfig().getDriverClass(),
                        EaglerXBungee.getEagler().getConfig().getAuthConfig().getDriverPath(), new Properties());
                if (conn == null) {
                    throw new IllegalStateException("Connection is null");
                }
            } catch (Throwable t) {
                throw new DefaultAuthSystem.AuthSystemException("Could not initialize '" + databaseURI + "'!", t);
            }
            try {
                try (Statement stmt = conn.createStatement()) {
                    var2[0] = var2[0].toLowerCase();
                    stmt.execute(
                            "CREATE TABLE IF NOT EXISTS \"banList\" (\"username\" TEXT PRIMARY KEY NOT NULL, \"expiration\" TIMESTAMP NOT NULL, \"reason\" TEXT, \"permanent\" INTEGER NOT NULL);");

                    String reason = var2.length > 1 ? String.join(" ", var2).substring(var2[0].length() + 1)
                            : "No reason given";
                    synchronized (this) {
                        // check if the player is already banned
                        String checkQuery = "SELECT * FROM banList WHERE username = ?";
                        try (PreparedStatement checkStmt = conn.prepareStatement(checkQuery)) {
                            checkStmt.setString(1, var2[0]);
                            try (ResultSet rs = checkStmt.executeQuery()) {
                                if (rs.next()) {
                                    var1.sendMessage(new TextComponent(ChatColor.RED + "That user is already banned"));
                                    return;
                                }
                            }
                        }

                        String insertQuery = "INSERT INTO banList (username, expiration, reason, permanent) VALUES (?, ?, ?, 1)";
                        try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) {
                            insertStmt.setString(1, var2[0]);
                            insertStmt.setTimestamp(2, new Timestamp(3155695200000L));
                            insertStmt.setString(3, reason);
                            insertStmt.execute();
                        }

                        if (isOnline) {
                            player.disconnect(
                                    new TextComponent(ChatColor.RED + "You have been banned from this server\nReason: " + reason));
                        }

                        var1.sendMessage(new TextComponent(ChatColor.RED + "Banned " + ChatColor.WHITE + var2[0]));
                    }
                } catch (SQLException e) {
                    try {
                        conn.close();
                    } catch (SQLException ex) {

                    }
                    throw new DefaultAuthSystem.AuthSystemException("Could not execute SQL statement!", e);
                }
            } catch (Throwable ex) {
                try {
                    conn.close();
                } catch (SQLException exx) {
                }
                throw ex;
            }
            try {
                conn.close();
            } catch (SQLException ex) {

            }
        }
    }
}
