package net.minecraft.world.item.crafting;

import net.minecraft.network.FriendlyByteBuf;
import com.google.gson.JsonElement;
import net.minecraft.world.item.ItemStack;
import net.minecraft.core.Registry;
import net.minecraft.world.level.ItemLike;
import net.minecraft.util.GsonHelper;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;

public class SimpleCookingSerializer<T extends AbstractCookingRecipe> implements RecipeSerializer<T> {
    private final int defaultCookingTime;
    private final CookieBaker<T> factory;
    
    public SimpleCookingSerializer(final CookieBaker<T> a, final int integer) {
        this.defaultCookingTime = integer;
        this.factory = a;
    }
    
    @Override
    public T fromJson(final ResourceLocation sm, final JsonObject jsonObject) {
        final String string4 = GsonHelper.getAsString(jsonObject, "group", "");
        final JsonElement jsonElement5 = GsonHelper.isArrayNode(jsonObject, "ingredient") ? GsonHelper.getAsJsonArray(jsonObject, "ingredient") : GsonHelper.getAsJsonObject(jsonObject, "ingredient");
        final Ingredient bgt6 = Ingredient.fromJson(jsonElement5);
        final String string5 = GsonHelper.getAsString(jsonObject, "result");
        final ResourceLocation sm2 = new ResourceLocation(string5);
        final Object o;
        final String str;
        final ItemStack ben9 = new ItemStack(Registry.ITEM.getOptional(sm2).<Throwable>orElseThrow(() -> {
            new IllegalStateException("Item: " + str + " does not exist");
            return o;
        }));
        final float float10 = GsonHelper.getAsFloat(jsonObject, "experience", 0.0f);
        final int integer11 = GsonHelper.getAsInt(jsonObject, "cookingtime", this.defaultCookingTime);
        return this.factory.create(sm, string4, bgt6, ben9, float10, integer11);
    }
    
    @Override
    public T fromNetwork(final ResourceLocation sm, final FriendlyByteBuf kv) {
        final String string4 = kv.readUtf(32767);
        final Ingredient bgt5 = Ingredient.fromNetwork(kv);
        final ItemStack ben6 = kv.readItem();
        final float float7 = kv.readFloat();
        final int integer8 = kv.readVarInt();
        return this.factory.create(sm, string4, bgt5, ben6, float7, integer8);
    }
    
    @Override
    public void toNetwork(final FriendlyByteBuf kv, final T bgi) {
        kv.writeUtf(bgi.group);
        bgi.ingredient.toNetwork(kv);
        kv.writeItem(bgi.result);
        kv.writeFloat(bgi.experience);
        kv.writeVarInt(bgi.cookingTime);
    }
    
    interface CookieBaker<T extends AbstractCookingRecipe> {
        T create(final ResourceLocation sm, final String string, final Ingredient bgt, final ItemStack ben, final float float5, final int integer);
    }
}
