// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers
//
// SPDX-License-Identifier: MPL-2.0

package dan200.computercraft.shared.data;

import com.mojang.serialization.MapCodec;
import dan200.computercraft.shared.computer.blocks.AbstractComputerBlockEntity;
import net.minecraft.util.context.ContextKey;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;

import java.util.Set;

/**
 * A loot condition which checks if the block entity has a computer ID.
 */
public final class HasComputerIdLootCondition implements LootItemCondition {
    public static final HasComputerIdLootCondition INSTANCE = new HasComputerIdLootCondition();
    public static final MapCodec<HasComputerIdLootCondition> CODEC = MapCodec.unit(HasComputerIdLootCondition.INSTANCE);
    public static final Builder BUILDER = () -> INSTANCE;

    private HasComputerIdLootCondition() {
    }

    @Override
    public boolean test(LootContext lootContext) {
        var tile = lootContext.getOptionalParameter(LootContextParams.BLOCK_ENTITY);
        return tile instanceof AbstractComputerBlockEntity computer && computer.getComputerID() >= 0;
    }

    @Override
    public Set<ContextKey<?>> getReferencedContextParams() {
        return Set.of(LootContextParams.BLOCK_ENTITY);
    }

    @Override
    public MapCodec<HasComputerIdLootCondition> codec() {
        return CODEC;
    }
}
