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 static land.chipmunk.chipmunkmod.command.CommandManager.literal;
import static land.chipmunk.chipmunkmod.command.CommandManager.argument;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger;
import static net.minecraft.command.argument.ItemStackArgumentType.itemStack;
import static net.minecraft.command.argument.ItemStackArgumentType.getItemStackArgument;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.client.MinecraftClient;
import net.minecraft.network.packet.c2s.play.CreativeInventoryActionC2SPacket;
import net.minecraft.item.ItemStack;
import net.minecraft.text.Text;

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

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

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

        final ItemStack stack = getItemStackArgument(context, "item").createStack(count, false);

        int slot = 36 + client.player.getInventory().selectedSlot;

        client.getNetworkHandler().getConnection().send(new CreativeInventoryActionC2SPacket(slot, stack));

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