package me.despawningbone.discordbot.command.admin;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;

import org.apache.commons.lang3.exception.ExceptionUtils;

import me.despawningbone.discordbot.DiscordBot;
import me.despawningbone.discordbot.command.Command;
import me.despawningbone.discordbot.command.CommandResult;
import me.despawningbone.discordbot.command.CommandResult.CommandResultType;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;

public class BotBan extends Command {
	public BotBan() {
		this.alias = Arrays.asList("bban");
		this.desc = "Ban a user from the bot";
		this.usage = "<userID>";
		this.examples = Arrays.asList(DiscordBot.OwnerID); 
		this.botUserLevel = BotUserLevel.BOT_MOD.ordinal();
	}

	@Override
	public CommandResult execute(TextChannel channel, User author, Message msg, String[] args) {
		if (args.length < 1) {
			return new CommandResult(CommandResultType.INVALIDARGS, "Please enter a user ID.");
		} else {
			String SID = args[0];
			Member b;
			try {
				b = channel.getGuild().getMemberById(SID);
			} catch (NumberFormatException e) {
				return new CommandResult(CommandResultType.INVALIDARGS, "Invalid user ID.");
			}
			if (b != null) {
				if (DiscordBot.ModID.contains(SID) || SID.equals(DiscordBot.BotID)) {
					return new CommandResult(CommandResultType.FAILURE, "That user cannot be banned.");
				} else {
					try (Connection con = DiscordBot.db.getConnection(); Statement s = con.createStatement()) {
						String reports = "";
						ResultSet uRs = s.executeQuery("SELECT reports FROM users WHERE id = " + SID + ";");
						
						if(uRs.next()) {
							reports = uRs.getString(1);
							if(reports.split("\n").length >= 5) {
								return new CommandResult(CommandResultType.FAILURE, "The user is already banned from the bot.");								
							}
						}
						
						PreparedStatement set = con.prepareStatement("INSERT INTO users(id, reports) VALUES (?, \"0\n0\n0\n0\n0\n\") ON CONFLICT(id) DO UPDATE SET reports = \"0\n0\n0\n0\n0\n\"");
						set.setString(1, SID);
						
						if(set.executeUpdate() != 0) {
							channel.sendMessage("You have successfully banned <@!" + SID + "> from the bot.").queue();
							return new CommandResult(CommandResultType.SUCCESS);							
						} else {
							throw new IllegalStateException("This should never happen");
						}
					} catch (SQLException e) {
						return new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(e));
					}
				}
			} else {
				return new CommandResult(CommandResultType.FAILURE, "This user ID is invalid.");
			}
		}		
	}
}
