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.config.EaglerAuthConfig;
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.text.DateFormat;
import java.util.Properties;

/**
 * Copyright (c) 2022-2023 lax1dude. All Rights Reserved.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 */
public class CommandTempBan extends Command {

	public CommandTempBan() {
		super("btempban", "eaglercraft.command.tempban");
	}

	@Override
	public void execute(CommandSender var1, String[] var2) {
		if (var2.length < 2) {
			var1.sendMessage(new TextComponent(
					ChatColor.RED + "How to use: " + ChatColor.WHITE + "/bungeetempban <player> <time> (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 > 2 ? String.join(" ", var2).substring(var2[0].length() + var2[1].length() + 2)
							: "No reason given";
					// parse time. 1d = 86400s, 1h = 3600s, 1m = 60s
					int time = Integer.parseInt(var2[1].substring(0, var2[1].length() - 1));
					char unit = var2[1].charAt(var2[1].length() - 1);
					long expiration = System.currentTimeMillis();
					switch (unit) {
						case 'd':
							expiration += time * 86400000;
							break;
						case 'h':
							expiration += time * 3600000;
							break;
						case 'm':
							expiration += time * 60000;
							break;
						case 's':
							expiration += time * 1000;
							break;
						default:
							var1.sendMessage(new TextComponent(ChatColor.RED + "Invalid time unit"));
							return;
					}
					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 (?, ?, ?, 0)";
						try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) {
							insertStmt.setString(1, var2[0]);
							insertStmt.setLong(2, expiration);
							insertStmt.setString(3, reason);
							insertStmt.execute();
						}
					
						if (isOnline) {
							player.disconnect(
									new TextComponent(ChatColor.RED + "You have been banned from this server\nReason: " + reason
											+ "\nExpires: " + DateFormat.getDateTimeInstance().format(expiration).replace(" ", " ")));
						}

						var1.sendMessage(new TextComponent(ChatColor.RED + "Temporarily banned " + ChatColor.WHITE + var2[0] + ChatColor.RED + " until " + ChatColor.WHITE + DateFormat.getDateTimeInstance().format(expiration).replace(" ", " ")));
					}
				} 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) {

			}
		}
	}
}
