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

import net.minecraft.util.GsonHelper;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import net.minecraft.util.Mth;
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.world.level.storage.loot.RandomValueBounds;
import org.apache.logging.log4j.Logger;

public class SetItemDamageFunction extends LootItemConditionalFunction {
    private static final Logger LOGGER;
    private final RandomValueBounds damage;
    
    private SetItemDamageFunction(final LootItemCondition[] arr, final RandomValueBounds csf) {
        super(arr);
        this.damage = csf;
    }
    
    public ItemStack run(final ItemStack ben, final LootContext crx) {
        if (ben.isDamageableItem()) {
            final float float4 = 1.0f - this.damage.getFloat(crx.getRandom());
            ben.setDamageValue(Mth.floor(float4 * ben.getMaxDamage()));
        }
        else {
            SetItemDamageFunction.LOGGER.warn("Couldn't set damage of loot item {}", ben);
        }
        return ben;
    }
    
    public static Builder<?> setDamage(final RandomValueBounds csf) {
        return LootItemConditionalFunction.simpleBuilder(arr -> new SetItemDamageFunction(arr, csf));
    }
    
    static {
        LOGGER = LogManager.getLogger();
    }
    
    public static class Serializer extends LootItemConditionalFunction.Serializer<SetItemDamageFunction> {
        protected Serializer() {
            super(new ResourceLocation("set_damage"), SetItemDamageFunction.class);
        }
        
        @Override
        public void serialize(final JsonObject jsonObject, final SetItemDamageFunction ctp, final JsonSerializationContext jsonSerializationContext) {
            super.serialize(jsonObject, ctp, jsonSerializationContext);
            jsonObject.add("damage", jsonSerializationContext.serialize(ctp.damage));
        }
        
        @Override
        public SetItemDamageFunction deserialize(final JsonObject jsonObject, final JsonDeserializationContext jsonDeserializationContext, final LootItemCondition[] arr) {
            return new SetItemDamageFunction(arr, GsonHelper.<RandomValueBounds>getAsObject(jsonObject, "damage", jsonDeserializationContext, RandomValueBounds.class), null);
        }
    }
}
