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 jt) {
        this.tag = jt;
    }
    
    public boolean matches(final ItemStack ben) {
        return this == NbtPredicate.ANY || this.matches(ben.getTag());
    }
    
    public boolean matches(final Entity akq) {
        return this == NbtPredicate.ANY || this.matches(getEntityTagToCompare(akq));
    }
    
    public boolean matches(@Nullable final Tag kj) {
        if (kj == null) {
            return this == NbtPredicate.ANY;
        }
        return this.tag == null || NbtUtils.compareNbt(this.tag, kj, 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 jt2;
        try {
            jt2 = TagParser.parseTag(GsonHelper.convertToString(jsonElement, "nbt"));
        }
        catch (CommandSyntaxException commandSyntaxException3) {
            throw new JsonSyntaxException("Invalid nbt tag: " + commandSyntaxException3.getMessage());
        }
        return new NbtPredicate(jt2);
    }
    
    public static CompoundTag getEntityTagToCompare(final Entity akq) {
        final CompoundTag jt2 = akq.saveWithoutId(new CompoundTag());
        if (akq instanceof Player) {
            final ItemStack ben3 = ((Player)akq).inventory.getSelected();
            if (!ben3.isEmpty()) {
                jt2.put("SelectedItem", ben3.save(new CompoundTag()));
            }
        }
        return jt2;
    }
    
    static {
        ANY = new NbtPredicate(null);
    }
}
