package com.infinityraider.agricraft.plugins.minecraft;

import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import com.infinityraider.infinitylib.utility.UnsafeUtil;
import net.minecraft.world.entity.animal.Chicken;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraftforge.fml.util.ObfuscationReflectionHelper;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.stream.Stream;

public class ChickenBreedItemInjector {
    public static void inject() {
        try {
            // Fetch field
            Class<Chicken> clazz = Chicken.class;
            Field field = ObfuscationReflectionHelper.findField(clazz, "field_6742");
            // Set accessible
            field.setAccessible(true);
            // Create new ingredient based on the old one and add the agricraft seed
            Ingredient ingredient = Ingredient.of(Stream.concat(
                    Arrays.stream(((Ingredient) field.get(null)).getItems()),
                    Stream.of(new ItemStack(AgriApi.getAgriContent().getItems().getSeedItem().toItem()))
            ));
            // Set the ingredient
            if(!UnsafeUtil.getInstance().replaceStaticField(field, ingredient)) {
                AgriCraft.instance.getLogger().error("Failed to inject AgriCraft seed as chicken feed");
            }
        } catch(Exception e) {
            AgriCraft.instance.getLogger().error("Failed to inject AgriCraft seed as chicken feed");
            AgriCraft.instance.getLogger().printStackTrace(e);
        }

    }
}

@@ -357,72 +357,42 @@
 nt;%0A
+%0A
 import 
-net.minecraftforge.fml.util.ObfuscationReflectionHelper;%0A
+javax.annotation.Nullable;
 %0Aimp
@@ -609,44 +609,36 @@
     
-Class%3CChicken%3E clazz = Chicken.class
+Field field = getFeedField()
 ;%0A  
@@ -651,150 +651,170 @@
     
-Field 
+if(
 field =
- ObfuscationReflectionHelper.findField(clazz, %22field_6742%22);%0A            // Set accessible%0A            field.setAccessible(true);
+= null) %7B%0A                AgriCraft.instance.getLogger().error(%22Failed to inject AgriCraft seed as chicken feed%22);%0A                return;%0A            %7D
 %0A   
@@ -1605,11 +1605,324 @@
 %7D%0A%0A    %7D
+%0A%0A    @Nullable%0A    private static Field getFeedField() %7B%0A        return Arrays.stream(Chicken.class.getDeclaredFields())%0A                .peek(field -%3E field.setAccessible(true))%0A                .filter(field -%3E field.getType() == Ingredient.class)%0A                .findAny()%0A                .orElse(null);%0A    %7D
 %0A%7D%0A

Fix chicken feed injection