package com.firefrostgaming.bitchbot;

import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.SignBlockEntity;
import net.minecraft.world.level.block.entity.SignText;
import net.minecraft.world.level.block.state.BlockState;

import java.util.List;

/**
 * Places oak signs at provided positions with up to 4 lines of text on the
 * front face. Used by Holly's spawn-area rules signs.
 *
 * NeoForge 1.21.1 sign API: SignBlockEntity#updateText(UnaryOperator, boolean front).
 */
public class SignPlacer {

    public static void placeAll(ServerLevel level, List<ProvisionConfig.RulesSign> signs) {
        int placed = 0;
        for (ProvisionConfig.RulesSign sign : signs) {
            try {
                BlockPos pos = new BlockPos(sign.position.x, sign.position.y, sign.position.z);
                BlockState state = Blocks.OAK_SIGN.defaultBlockState();
                level.setBlock(pos, state, 2);

                BlockEntity be = level.getBlockEntity(pos);
                if (be instanceof SignBlockEntity sbe) {
                    Component[] lines = new Component[4];
                    for (int i = 0; i < 4; i++) {
                        String line = (sign.lines != null && i < sign.lines.size()) ? sign.lines.get(i) : "";
                        lines[i] = Component.literal(line);
                    }
                    SignText text = sbe.getFrontText()
                            .setMessage(0, lines[0])
                            .setMessage(1, lines[1])
                            .setMessage(2, lines[2])
                            .setMessage(3, lines[3]);
                    sbe.setText(text, true);
                    sbe.setChanged();
                    placed++;
                }
            } catch (Throwable t) {
                BitchBot.LOGGER.error("[BitchBot] Failed to place sign: {}", t.getMessage());
            }
        }
        BitchBot.LOGGER.info("[BitchBot] Rules signs placed: {} / {}", placed, signs.size());
    }
}
