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.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.User;

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

	@Override   //DONE rewrite BotBan/BotUnban to use SQLite
	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 t = channel.getGuild().getMemberById(SID);
			if (t != null) {
				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) {
							//can actually just UPDATE since it must have an entry 
							PreparedStatement set = con.prepareStatement("INSERT INTO users(id, reports) VALUES (?, \"\") ON CONFLICT(id) DO UPDATE SET reports = \"\"");
							set.setString(1, SID);
							if(set.executeUpdate() != 0) {
								channel.sendMessage("You unbanned <@!" + SID + ">.").queue();
								return new CommandResult(CommandResultType.SUCCESS);							
							} else {
								throw new IllegalStateException("This should never happen");
							}
						}
					}
					return new CommandResult(CommandResultType.FAILURE, "This user is not banned.");
				} catch (SQLException e) {
					return new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(e));
				}
			} else {
				return new CommandResult(CommandResultType.FAILURE, "This user ID is invalid.");
			}
		}
	}
}
