package moe.kyokobot.music.commands;

import moe.kyokobot.bot.command.CommandContext;
import moe.kyokobot.bot.util.CommonErrors;
import moe.kyokobot.music.MusicIcons;
import moe.kyokobot.music.MusicManager;
import moe.kyokobot.music.MusicPlayer;
import moe.kyokobot.music.MusicQueue;
import org.jetbrains.annotations.NotNull;
import org.jsoup.helper.StringUtil;

import javax.annotation.Nonnull;
import java.util.Map;

import static java.lang.Integer.parseUnsignedInt;
import static moe.kyokobot.bot.util.StringUtil.markdown;

public class RemoveCommand extends MusicCommand {

    private final MusicManager musicManager;
    private static final int BASE_TEN = 10;

    public RemoveCommand(MusicManager musicManager) {
        this.musicManager = musicManager;

        checkChannel = true;
        name = "remove";
    }

    @Override
    public void execute(@NotNull @Nonnull CommandContext context) {
        var state = context.selfVoiceState();
        if (state != null && state.channel() != null) {
            MusicPlayer player = musicManager.getMusicPlayer(context.guild());
            MusicQueue queue = musicManager.getQueue(context.guild());

            if (!player.isConnected()) {
                context.error("music.queueempty", Map.of("prefix", context.prefix()));
                musicManager.dispose(context.guild());
            }

            if (context.hasArgs()) {
                String query = context.concatArgs().trim();
                if (StringUtil.isNumeric(query)) {
                    int index = parseUnsignedInt(query, BASE_TEN) - 1;
                    if ((index < 0) || (index >= queue.getTracks().size())) {
                        context.error("music.invalidindex", Map.of("index", query));
                    } else {
                        context.send(MusicIcons.REMOVE + context.icu("music.removed", Map.of("song",
                                markdown(queue.getTracks().get(index).getAudioTrack().getInfo().title))));
                        queue.remove(index);
                    }
                    return;
                } else if (query.equals("~")) {
                    queue.removeDuplicates();
                    context.send(MusicIcons.REMOVE + context.translated("music.remove.duplicates"));
                    return;
                } else if (query.matches("<@([0-9])+>")) {
                    String trimmedQuery = query.substring(2, query.length() - 1);
                    queue.removeUser(trimmedQuery);
                    context.send(MusicIcons.REMOVE + context.icu("music.remove.user", Map.of("user", query)));
                    return;
                }
            }
            CommonErrors.usage(context);
        } else {
            context.error(context.translated("music.joinchannel"));
        }
    }
}