package com.thebrokenrail.gestus.command;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.thebrokenrail.gestus.Gestus;
import com.thebrokenrail.gestus.emote.EmoteRegistry;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.command.argument.IdentifierArgumentType;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.CommandSource;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.LiteralText;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Identifier;

import java.util.Collection;
import java.util.Collections;

public class EmoteCommand {
    private static final DynamicCommandExceptionType NOT_FOUND_EXCEPTION = new DynamicCommandExceptionType(object -> new LiteralText(new TranslatableText("command." + Gestus.NAMESPACE + ".emote.unknown_emote", object).getString()));

    public static void register(CommandDispatcher<ServerCommandSource> dispatcher) {
        dispatcher.register(CommandManager.literal("emote")
                .then(CommandManager.argument("emote", IdentifierArgumentType.identifier())
                        .suggests((ctx, builder) -> ctx.getSource() != null ? CommandSource.suggestIdentifiers(EmoteRegistry.getAll(), builder) : Suggestions.empty())
                        .executes(ctx -> run(ctx, Collections.singletonList(ctx.getSource().getPlayer())))
                        .then(CommandManager.argument("player", EntityArgumentType.players())
                                .requires(source -> source.hasPermissionLevel(2))
                                .executes(ctx -> run(ctx, EntityArgumentType.getPlayers(ctx, "player")))
                        )
                )
        );
    }

    private static int run(CommandContext<ServerCommandSource> ctx, Collection<ServerPlayerEntity> players) throws CommandSyntaxException {
        Identifier emote = IdentifierArgumentType.getIdentifier(ctx, "emote");
        if (EmoteRegistry.get(emote) != null) {
            int i = 0;
            for (ServerPlayerEntity player : players) {
                if (player != null) {
                    Gestus.playCustomEmote(player, emote);
                    i++;
                }
            }
            ctx.getSource().sendFeedback(new LiteralText(new TranslatableText("command." + Gestus.NAMESPACE + ".emote.playing_emote").getString()), false);
            return i;
        } else {
            throw NOT_FOUND_EXCEPTION.create(emote);
        }
    }
}
