package land.chipmunk.chipmunkmod.commands;

import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ServerboundSetCreativeModeSlotPacket;
import net.minecraft.world.item.ItemStack;

import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static land.chipmunk.chipmunkmod.command.CommandManager.argument;
import static land.chipmunk.chipmunkmod.command.CommandManager.literal;
import static net.minecraft.commands.arguments.item.ItemArgument.getItem;
import static net.minecraft.commands.arguments.item.ItemArgument.item;

public class ItemCommand {
    public static void register (final CommandDispatcher<FabricClientCommandSource> dispatcher, final CommandBuildContext commandRegistryAccess) {
        dispatcher.register(
                literal("item")
                        .then(
                                argument("item", item(commandRegistryAccess))
                                        .executes(c -> setItem(c, 1))
                                        .then(argument("count", integer(1, 64))
                                                      .executes(ItemCommand::setItem))
                        )
        );
    }

    public static int setItem (final CommandContext<FabricClientCommandSource> context) throws CommandSyntaxException {
        return setItem(context, getInteger(context, "count"));
    }

    public static int setItem (final CommandContext<FabricClientCommandSource> context, final int count) throws CommandSyntaxException {
        final FabricClientCommandSource source = context.getSource();
        final Minecraft client = source.getClient();

        final LocalPlayer player = client.player;
        final ClientPacketListener connection = client.getConnection();

        if (player == null || connection == null) return Command.SINGLE_SUCCESS;

        final ItemStack stack = getItem(context, "item").createItemStack(count);

        final int slot = 36 + player.getInventory().getSelectedSlot();
        connection.send(new ServerboundSetCreativeModeSlotPacket(slot, stack));

        source.sendFeedback(
                Component.translatable(
                        "Replaced your held item with %s %s",
                        Component.literal(String.valueOf(count)),
                        stack.getDisplayName()
                )
        );
        return Command.SINGLE_SUCCESS;
    }
}
