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 net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.core.BlockPos;
import net.minecraft.advancements.critereon.LocationPredicate;

public class LocationCheck implements LootItemCondition {
    private final LocationPredicate predicate;
    private final BlockPos offset;
    
    public LocationCheck(final LocationPredicate bp, final BlockPos fk) {
        this.predicate = bp;
        this.offset = fk;
    }
    
    @Override
    public boolean test(final LootContext crx) {
        final BlockPos fk3 = crx.<BlockPos>getParamOrNull(LootContextParams.BLOCK_POS);
        return fk3 != null && this.predicate.matches(crx.getLevel(), (float)(fk3.getX() + this.offset.getX()), (float)(fk3.getY() + this.offset.getY()), (float)(fk3.getZ() + this.offset.getZ()));
    }
    
    public static Builder checkLocation(final LocationPredicate.Builder a) {
        return () -> new LocationCheck(a.build(), BlockPos.ZERO);
    }
    
    public static class Serializer extends LootItemCondition.Serializer<LocationCheck> {
        public Serializer() {
            super(new ResourceLocation("location_check"), LocationCheck.class);
        }
        
        @Override
        public void serialize(final JsonObject jsonObject, final LocationCheck cuk, final JsonSerializationContext jsonSerializationContext) {
            jsonObject.add("predicate", cuk.predicate.serializeToJson());
            if (cuk.offset.getX() != 0) {
                jsonObject.addProperty("offsetX", cuk.offset.getX());
            }
            if (cuk.offset.getY() != 0) {
                jsonObject.addProperty("offsetY", cuk.offset.getY());
            }
            if (cuk.offset.getZ() != 0) {
                jsonObject.addProperty("offsetZ", cuk.offset.getZ());
            }
        }
        
        @Override
        public LocationCheck deserialize(final JsonObject jsonObject, final JsonDeserializationContext jsonDeserializationContext) {
            final LocationPredicate bp4 = LocationPredicate.fromJson(jsonObject.get("predicate"));
            final int integer5 = GsonHelper.getAsInt(jsonObject, "offsetX", 0);
            final int integer6 = GsonHelper.getAsInt(jsonObject, "offsetY", 0);
            final int integer7 = GsonHelper.getAsInt(jsonObject, "offsetZ", 0);
            return new LocationCheck(bp4, new BlockPos(integer5, integer6, integer7));
        }
    }
}
