package net.minecraft.world.level.storage.loot.functions;

import com.google.gson.JsonSyntaxException;
import net.minecraft.util.GsonHelper;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonArray;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.world.item.EnchantedBookItem;
import net.minecraft.world.item.enchantment.EnchantmentInstance;
import net.minecraft.world.level.ItemLike;
import net.minecraft.util.Mth;
import net.minecraft.world.item.Items;
import net.minecraft.core.Registry;
import com.google.common.collect.Lists;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.item.ItemStack;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.item.enchantment.Enchantment;
import java.util.List;
import org.apache.logging.log4j.Logger;

public class EnchantRandomlyFunction extends LootItemConditionalFunction {
    private static final Logger LOGGER;
    private final List<Enchantment> enchantments;
    
    private EnchantRandomlyFunction(final LootItemCondition[] arr, final Collection<Enchantment> collection) {
        super(arr);
        this.enchantments = ImmutableList.copyOf(collection);
    }
    
    public ItemStack run(ItemStack ben, final LootContext crx) {
        final Random random5 = crx.getRandom();
        Enchantment bhx9;
        if (this.enchantments.isEmpty()) {
            final List<Enchantment> list6 = Lists.newArrayList();
            for (final Enchantment bhx8 : Registry.ENCHANTMENT) {
                if (ben.getItem() == Items.BOOK || bhx8.canEnchant(ben)) {
                    list6.add(bhx8);
                }
            }
            if (list6.isEmpty()) {
                EnchantRandomlyFunction.LOGGER.warn("Couldn't find a compatible enchantment for {}", ben);
                return ben;
            }
            bhx9 = list6.get(random5.nextInt(list6.size()));
        }
        else {
            bhx9 = this.enchantments.get(random5.nextInt(this.enchantments.size()));
        }
        final int integer6 = Mth.nextInt(random5, bhx9.getMinLevel(), bhx9.getMaxLevel());
        if (ben.getItem() == Items.BOOK) {
            ben = new ItemStack(Items.ENCHANTED_BOOK);
            EnchantedBookItem.addEnchantment(ben, new EnchantmentInstance(bhx9, integer6));
        }
        else {
            ben.enchant(bhx9, integer6);
        }
        return ben;
    }
    
    public static Builder<?> randomApplicableEnchantment() {
        return LootItemConditionalFunction.simpleBuilder(arr -> new EnchantRandomlyFunction(arr, ImmutableList.of()));
    }
    
    static {
        LOGGER = LogManager.getLogger();
    }
    
    public static class Serializer extends LootItemConditionalFunction.Serializer<EnchantRandomlyFunction> {
        public Serializer() {
            super(new ResourceLocation("enchant_randomly"), EnchantRandomlyFunction.class);
        }
        
        @Override
        public void serialize(final JsonObject jsonObject, final EnchantRandomlyFunction ctb, final JsonSerializationContext jsonSerializationContext) {
            super.serialize(jsonObject, ctb, jsonSerializationContext);
            if (!ctb.enchantments.isEmpty()) {
                final JsonArray jsonArray5 = new JsonArray();
                for (final Enchantment bhx7 : ctb.enchantments) {
                    final ResourceLocation sm8 = Registry.ENCHANTMENT.getKey(bhx7);
                    if (sm8 == null) {
                        throw new IllegalArgumentException("Don't know how to serialize enchantment " + bhx7);
                    }
                    jsonArray5.add(new JsonPrimitive(sm8.toString()));
                }
                jsonObject.add("enchantments", jsonArray5);
            }
        }
        
        @Override
        public EnchantRandomlyFunction deserialize(final JsonObject jsonObject, final JsonDeserializationContext jsonDeserializationContext, final LootItemCondition[] arr) {
            final List<Enchantment> list5 = Lists.newArrayList();
            if (jsonObject.has("enchantments")) {
                final JsonArray jsonArray6 = GsonHelper.getAsJsonArray(jsonObject, "enchantments");
                for (final JsonElement jsonElement8 : jsonArray6) {
                    final String string9 = GsonHelper.convertToString(jsonElement8, "enchantment");
                    final Object o;
                    final String str;
                    final Enchantment bhx10 = Registry.ENCHANTMENT.getOptional(new ResourceLocation(string9)).<Throwable>orElseThrow(() -> {
                        new JsonSyntaxException("Unknown enchantment '" + str + "'");
                        return o;
                    });
                    list5.add(bhx10);
                }
            }
            return new EnchantRandomlyFunction(arr, list5, null);
        }
    }
}
