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 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 dbb) {
        super(arr);
        this.damage = dbb;
    }
    
    @Override
    public LootItemFunctionType getType() {
        return LootItemFunctions.SET_DAMAGE;
    }
    
    public ItemStack run(final ItemStack bki, final LootContext dat) {
        if (bki.isDamageableItem()) {
            final float float4 = 1.0f - this.damage.getFloat(dat.getRandom());
            bki.setDamageValue(Mth.floor(float4 * bki.getMaxDamage()));
        }
        else {
            SetItemDamageFunction.LOGGER.warn("Couldn't set damage of loot item {}", bki);
        }
        return bki;
    }
    
    public static Builder<?> setDamage(final RandomValueBounds dbb) {
        return LootItemConditionalFunction.simpleBuilder(arr -> new SetItemDamageFunction(arr, dbb));
    }
    
    static {
        LOGGER = LogManager.getLogger();
    }
    
    public static class Serializer extends LootItemConditionalFunction.Serializer<SetItemDamageFunction> {
        @Override
        public void serialize(final JsonObject jsonObject, final SetItemDamageFunction dcp, final JsonSerializationContext jsonSerializationContext) {
            super.serialize(jsonObject, dcp, jsonSerializationContext);
            jsonObject.add("damage", jsonSerializationContext.serialize(dcp.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);
        }
    }
}
