package net.minecraft.advancements.critereon;

import net.minecraft.world.entity.player.Player;
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.JsonPrimitive;
import com.google.gson.JsonNull;
import com.google.gson.JsonElement;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.world.entity.Entity;
import net.minecraft.nbt.Tag;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nullable;
import net.minecraft.nbt.CompoundTag;

public class NbtPredicate {
    public static final NbtPredicate ANY;
    @Nullable
    private final CompoundTag tag;
    
    public NbtPredicate(@Nullable final CompoundTag le) {
        this.tag = le;
    }
    
    public boolean matches(final ItemStack bki) {
        return this == NbtPredicate.ANY || this.matches(bki.getTag());
    }
    
    public boolean matches(final Entity aom) {
        return this == NbtPredicate.ANY || this.matches(getEntityTagToCompare(aom));
    }
    
    public boolean matches(@Nullable final Tag lu) {
        if (lu == null) {
            return this == NbtPredicate.ANY;
        }
        return this.tag == null || NbtUtils.compareNbt(this.tag, lu, true);
    }
    
    public JsonElement serializeToJson() {
        if (this == NbtPredicate.ANY || this.tag == null) {
            return JsonNull.INSTANCE;
        }
        return new JsonPrimitive(this.tag.toString());
    }
    
    public static NbtPredicate fromJson(@Nullable final JsonElement jsonElement) {
        if (jsonElement == null || jsonElement.isJsonNull()) {
            return NbtPredicate.ANY;
        }
        CompoundTag le2;
        try {
            le2 = TagParser.parseTag(GsonHelper.convertToString(jsonElement, "nbt"));
        }
        catch (CommandSyntaxException commandSyntaxException3) {
            throw new JsonSyntaxException("Invalid nbt tag: " + commandSyntaxException3.getMessage());
        }
        return new NbtPredicate(le2);
    }
    
    public static CompoundTag getEntityTagToCompare(final Entity aom) {
        final CompoundTag le2 = aom.saveWithoutId(new CompoundTag());
        if (aom instanceof Player) {
            final ItemStack bki3 = ((Player)aom).inventory.getSelected();
            if (!bki3.isEmpty()) {
                le2.put("SelectedItem", bki3.save(new CompoundTag()));
            }
        }
        return le2;
    }
    
    static {
        ANY = new NbtPredicate(null);
    }
}
