package com.tiedup.remake.worldgen;

import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.Optional;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureType;
import net.minecraft.world.level.levelgen.structure.pieces.StructurePiecesBuilder;

/**
 * Hanging Cage Structure - Underground cage suspended from cave ceiling.
 *
 * Places a Pet Cage hanging from iron bars in a cave, with a Damsel inside.
 * 25% chance of shiny damsel variant.
 * The cage must be at least 4 blocks above the cave floor.
 */
public class HangingCageStructure extends Structure {

    public static final Codec<HangingCageStructure> CODEC =
        RecordCodecBuilder.create(instance ->
            instance
                .group(settingsCodec(instance))
                .apply(instance, HangingCageStructure::new)
        );

    public HangingCageStructure(StructureSettings settings) {
        super(settings);
    }

    @Override
    protected Optional<GenerationStub> findGenerationPoint(
        GenerationContext context
    ) {
        // Choose a random Y between -20 and 40 for cave search
        int y = context.random().nextIntBetweenInclusive(-20, 40);

        // Center of the chunk
        BlockPos pos = new BlockPos(
            context.chunkPos().getMiddleBlockX(),
            y,
            context.chunkPos().getMiddleBlockZ()
        );

        return Optional.of(
            new GenerationStub(pos, builder -> {
                generatePieces(builder, context, pos);
            })
        );
    }

    private void generatePieces(
        StructurePiecesBuilder builder,
        GenerationContext context,
        BlockPos pos
    ) {
        builder.addPiece(new HangingCagePiece(pos, context.random()));
    }

    @Override
    public StructureType<?> type() {
        return ModStructures.HANGING_CAGE.get();
    }
}
