package me.despawningbone.discordbot.command.admin;

import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;

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.Permission;
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 Purge extends Command {
	public Purge() {
		this.desc = "Clear the bot's message";
		this.usage = "<count>";
		this.remarks = Arrays.asList("Note: Count must be in between 1 to 100, and it includes the messages in between.");
		this.botUserLevel = -BotUserLevel.BOT_MOD.ordinal();
		this.examples = Arrays.asList("20");
		this.perms = EnumSet.of(Permission.MESSAGE_MANAGE);
	}

	@Override  //TODO rewrite purge to purge until message deleted meet the count instead
	public CommandResult execute(TextChannel channel, User author, Message msg, String[] args) {
		int n = 0;
		try {
			n = Integer.parseInt(args[0]);
		} catch (NumberFormatException e) {
			return new CommandResult(CommandResultType.INVALIDARGS, "Please enter a correct number.");
		} catch (ArrayIndexOutOfBoundsException e) {
			return new CommandResult(CommandResultType.INVALIDARGS, "Please enter a number.");
		}
		if (n > 100) {
			return new CommandResult(CommandResultType.INVALIDARGS, "The number entered is too large.");
		}
		
		channel.getHistory().retrievePast(n).queue(history -> {
			List<Message> msgs = history.stream()
			.filter(hmsg -> hmsg.getAuthor().getId().equals(DiscordBot.BotID)).collect(Collectors.toList());
			
			if(msgs.size() > 1 && channel.getGuild().getSelfMember().hasPermission(Permission.MESSAGE_MANAGE)) channel.deleteMessages(msgs).queue();
			else msgs.forEach(m -> channel.deleteMessageById(m.getId()).queue());
			//if no result ignore
		});
		
		return new CommandResult(CommandResultType.SUCCESS);
	}

}
