package cz.jzitnik.tui.utils;

import cz.jzitnik.game.Game;

/**
 * Utility class for rendering numeric sprites (e.g. hotbar numbers) in the terminal UI.
 * Ensures fixed-size output suitable for consistent rendering in UI components like hotbars.
 */
public class Numbers {
    /**
     * Pads and formats a rendered number string to fit exactly into a 50x25 cell block,
     * typically used in the hotbar UI.
     *
     * @param str    The raw rendered number string (multi-line).
     * @param height The actual height of the rendered string.
     * @param width  The actual width of the rendered string.
     * @return A formatted and padded string of exactly 50x25 characters.
     */
    public static String fixForHotbar(String str, int height, int width) {
        var parts = str.split("\n");
        // Make it 50x25
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < 24 - height; i++) {
            stringBuilder.append("\033[0m ".repeat(50)).append("\n");
        }

        for (int i = 0; i < height; i++) {
            stringBuilder.append("\033[0m ".repeat(48 - width));
            stringBuilder.append(parts[i]);

            stringBuilder.append("\033[49m ".repeat(2));
            stringBuilder.append("\n");
        }
        stringBuilder.append("\033[0m ".repeat(50)).append("\n");

        return stringBuilder.toString();
    }

    /**
     * Returns a string representation of the number formatted as a 50x25 character sprite.
     * This is used to display hotbar slot numbers in a consistent visual size.
     *
     * @param number The number to render (1–9).
     * @param game   The game context, used to retrieve font resources.
     * @return The formatted and fixed-size sprite string representing the number.
     */
    public static String getNumberSprite(int number, Game game) {
        if (number == 1) {
            StringBuilder sprite = new StringBuilder();
            for (int i = 0; i < 25; i++) {
                sprite.append("\033[0m ".repeat(50));
                sprite.append("\n");
            }
            return sprite.toString();
        }

        var font = game.getGameStates().dependencies.font;
        var text = font.getLine(String.valueOf(number), "[47m", "[49m");
        var scaled = text;

        return fixForHotbar(scaled.getData(), scaled.getHeight(), scaled.getWidth());
    }
}
