package net.minecraft.advancements.critereon;

import com.google.gson.JsonElement;
import net.minecraft.advancements.CriterionTriggerInstance;
import net.minecraft.world.item.ItemStack;
import net.minecraft.server.level.ServerPlayer;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;

public class ItemDurabilityTrigger extends SimpleCriterionTrigger<TriggerInstance> {
    private static final ResourceLocation ID;
    
    @Override
    public ResourceLocation getId() {
        return ItemDurabilityTrigger.ID;
    }
    
    @Override
    public TriggerInstance createInstance(final JsonObject jsonObject, final JsonDeserializationContext jsonDeserializationContext) {
        final ItemPredicate bj4 = ItemPredicate.fromJson(jsonObject.get("item"));
        final MinMaxBounds.Ints d5 = MinMaxBounds.Ints.fromJson(jsonObject.get("durability"));
        final MinMaxBounds.Ints d6 = MinMaxBounds.Ints.fromJson(jsonObject.get("delta"));
        return new TriggerInstance(bj4, d5, d6);
    }
    
    public void trigger(final ServerPlayer xe, final ItemStack ben, final int integer) {
        this.trigger(xe.getAdvancements(), a -> a.matches(ben, integer));
    }
    
    static {
        ID = new ResourceLocation("item_durability_changed");
    }
    
    public static class TriggerInstance extends AbstractCriterionTriggerInstance {
        private final ItemPredicate item;
        private final MinMaxBounds.Ints durability;
        private final MinMaxBounds.Ints delta;
        
        public TriggerInstance(final ItemPredicate bj, final MinMaxBounds.Ints d2, final MinMaxBounds.Ints d3) {
            super(ItemDurabilityTrigger.ID);
            this.item = bj;
            this.durability = d2;
            this.delta = d3;
        }
        
        public static TriggerInstance changedDurability(final ItemPredicate bj, final MinMaxBounds.Ints d) {
            return new TriggerInstance(bj, d, MinMaxBounds.Ints.ANY);
        }
        
        public boolean matches(final ItemStack ben, final int integer) {
            return this.item.matches(ben) && this.durability.matches(ben.getMaxDamage() - integer) && this.delta.matches(ben.getDamageValue() - integer);
        }
        
        @Override
        public JsonElement serializeToJson() {
            final JsonObject jsonObject2 = new JsonObject();
            jsonObject2.add("item", this.item.serializeToJson());
            jsonObject2.add("durability", this.durability.serializeToJson());
            jsonObject2.add("delta", this.delta.serializeToJson());
            return jsonObject2;
        }
    }
}
