package net.minecraft.network.protocol.game;

import net.minecraft.network.PacketListener;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.core.Registry;
import net.minecraft.world.item.crafting.RecipeSerializer;
import java.util.Iterator;
import java.io.IOException;
import net.minecraft.network.FriendlyByteBuf;
import com.google.common.collect.Lists;
import java.util.Collection;
import net.minecraft.world.item.crafting.Recipe;
import java.util.List;
import net.minecraft.network.protocol.Packet;

public class ClientboundUpdateRecipesPacket implements Packet<ClientGamePacketListener> {
    private List<Recipe<?>> recipes;
    
    public ClientboundUpdateRecipesPacket() {
    }
    
    public ClientboundUpdateRecipesPacket(final Collection<Recipe<?>> collection) {
        this.recipes = Lists.newArrayList(collection);
    }
    
    @Override
    public void handle(final ClientGamePacketListener lw) {
        lw.handleUpdateRecipes(this);
    }
    
    @Override
    public void read(final FriendlyByteBuf kv) throws IOException {
        this.recipes = Lists.newArrayList();
        for (int integer3 = kv.readVarInt(), integer4 = 0; integer4 < integer3; ++integer4) {
            this.recipes.add(fromNetwork(kv));
        }
    }
    
    @Override
    public void write(final FriendlyByteBuf kv) throws IOException {
        kv.writeVarInt(this.recipes.size());
        for (final Recipe<?> bgw4 : this.recipes) {
            ClientboundUpdateRecipesPacket.<Recipe<?>>toNetwork(bgw4, kv);
        }
    }
    
    public List<Recipe<?>> getRecipes() {
        return this.recipes;
    }
    
    public static Recipe<?> fromNetwork(final FriendlyByteBuf kv) {
        final ResourceLocation sm2 = kv.readResourceLocation();
        final ResourceLocation sm3 = kv.readResourceLocation();
        final Object o;
        final Object obj;
        return Registry.RECIPE_SERIALIZER.getOptional(sm2).<Throwable>orElseThrow(() -> {
            new IllegalArgumentException("Unknown recipe serializer " + obj);
            return o;
        }).fromNetwork(sm3, kv);
    }
    
    public static <T extends Recipe<?>> void toNetwork(final T bgw, final FriendlyByteBuf kv) {
        kv.writeResourceLocation(Registry.RECIPE_SERIALIZER.getKey(bgw.getSerializer()));
        kv.writeResourceLocation(bgw.getId());
        bgw.getSerializer().toNetwork(kv, bgw);
    }
}
