/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.dungeon;

import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.entity.BlockEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

public class BatchPlacer {
    private static final Logger LOGGER = LogManager.getLogger(BatchPlacer.class);

    private final ServerLevel level;
    private final PlacementData data;
    private int blockIndex = 0;
    private int entityIndex = 0;

    public BatchPlacer(ServerLevel level, PlacementData data) {
        this.level = level;
        this.data = data;
    }

    public boolean placeNextBatch() {
        List<BlockPlacement> blocks = data.blocks();
        int batchSize = 16;
        int blockEnd = Math.min(blockIndex + batchSize, blocks.size());
        for (int i = blockIndex; i < blockEnd; i++) {
            BlockPlacement bp = blocks.get(i);
            level.setBlock(bp.pos(), bp.state(), 3);
            if (bp.nbt() != null) {
                BlockEntity be = level.getBlockEntity(bp.pos());
                if (be != null) {
                    be.loadWithComponents(bp.nbt(), level.registryAccess());
                }
            }
        }
        blockIndex = blockEnd;

        if (blockIndex >= blocks.size() && entityIndex < data.entities().size()) {
            for (EntityPlacement ep : data.entities()) {
                ep.spawn(level);
            }
            entityIndex = data.entities().size();
            return false;
        }
        return blockIndex < blocks.size();
    }
}