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

import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.google.gson.JsonSyntaxException;
import net.minecraft.nbt.TagParser;
import net.minecraft.util.GsonHelper;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonObject;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.nbt.CompoundTag;

public class SetNbtFunction extends LootItemConditionalFunction {
    private final CompoundTag tag;
    
    private SetNbtFunction(final LootItemCondition[] arr, final CompoundTag le) {
        super(arr);
        this.tag = le;
    }
    
    @Override
    public LootItemFunctionType getType() {
        return LootItemFunctions.SET_NBT;
    }
    
    public ItemStack run(final ItemStack bki, final LootContext dat) {
        bki.getOrCreateTag().merge(this.tag);
        return bki;
    }
    
    public static Builder<?> setTag(final CompoundTag le) {
        return LootItemConditionalFunction.simpleBuilder(arr -> new SetNbtFunction(arr, le));
    }
    
    public static class Serializer extends LootItemConditionalFunction.Serializer<SetNbtFunction> {
        @Override
        public void serialize(final JsonObject jsonObject, final SetNbtFunction dcs, final JsonSerializationContext jsonSerializationContext) {
            super.serialize(jsonObject, dcs, jsonSerializationContext);
            jsonObject.addProperty("tag", dcs.tag.toString());
        }
        
        @Override
        public SetNbtFunction deserialize(final JsonObject jsonObject, final JsonDeserializationContext jsonDeserializationContext, final LootItemCondition[] arr) {
            try {
                final CompoundTag le5 = TagParser.parseTag(GsonHelper.getAsString(jsonObject, "tag"));
                return new SetNbtFunction(arr, le5, null);
            }
            catch (CommandSyntaxException commandSyntaxException5) {
                throw new JsonSyntaxException(commandSyntaxException5.getMessage());
            }
        }
    }
}
