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

import net.minecraft.util.GsonHelper;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.ValidationContext;
import net.minecraft.resources.ResourceLocation;
import org.apache.logging.log4j.Logger;

public class ConditionReference implements LootItemCondition {
    private static final Logger LOGGER;
    private final ResourceLocation name;
    
    public ConditionReference(final ResourceLocation sm) {
        this.name = sm;
    }
    
    @Override
    public void validate(final ValidationContext csg) {
        if (csg.hasVisitedCondition(this.name)) {
            csg.reportProblem("Condition " + this.name + " is recursively called");
            return;
        }
        super.validate(csg);
        final LootItemCondition cum3 = csg.resolveCondition(this.name);
        if (cum3 == null) {
            csg.reportProblem("Unknown condition table called " + this.name);
        }
        else {
            cum3.validate(csg.enterTable(".{" + this.name + "}", this.name));
        }
    }
    
    @Override
    public boolean test(final LootContext crx) {
        final LootItemCondition cum3 = crx.getCondition(this.name);
        if (crx.addVisitedCondition(cum3)) {
            try {
                return cum3.test(crx);
            }
            finally {
                crx.removeVisitedCondition(cum3);
            }
        }
        ConditionReference.LOGGER.warn("Detected infinite loop in loot tables");
        return false;
    }
    
    static {
        LOGGER = LogManager.getLogger();
    }
    
    public static class Serializer extends LootItemCondition.Serializer<ConditionReference> {
        protected Serializer() {
            super(new ResourceLocation("reference"), ConditionReference.class);
        }
        
        @Override
        public void serialize(final JsonObject jsonObject, final ConditionReference cue, final JsonSerializationContext jsonSerializationContext) {
            jsonObject.addProperty("name", cue.name.toString());
        }
        
        @Override
        public ConditionReference deserialize(final JsonObject jsonObject, final JsonDeserializationContext jsonDeserializationContext) {
            final ResourceLocation sm4 = new ResourceLocation(GsonHelper.getAsString(jsonObject, "name"));
            return new ConditionReference(sm4);
        }
    }
}
