package cz.jzitnik.game.ui;

import cz.jzitnik.game.Game;
import cz.jzitnik.game.SpriteLoader;
import cz.jzitnik.game.sprites.Heart;
import cz.jzitnik.game.sprites.Hunger;
import cz.jzitnik.tui.SpriteList;
import org.jline.terminal.Terminal;

import static cz.jzitnik.game.ui.Inventory.INVENTORY_SIZE_PX;

/**
 * A utility class for rendering the player's health and hunger bars.
 * The bars are displayed in a graphical form using text sprites.
 */
public class Healthbar {

    /**
     * Renders the health and hunger bar of the player using sprite graphics.
     *
     * <p>This method uses the terminal width to position the bars, and pulls sprite data from the
     * provided {@link SpriteList} to render the correct number of hearts and hunger icons
     * based on the player's current health and hunger levels.</p>
     *
     * @param buffer     The StringBuilder to which the rendering output is appended.
     * @param spriteList The list of sprites used for rendering the hearts and hunger icons.
     * @param terminal   The terminal from which screen width is obtained.
     * @param game       The current game instance, from which player state is read.
     */
    public static void render(StringBuilder buffer, SpriteList spriteList, Terminal terminal, Game game) {
        int termWidth = terminal.getWidth();
        int startLeft = Math.max(0, (termWidth / 2) - (INVENTORY_SIZE_PX / 2));

        int heartSize = 9 * 20;
        int moveLeft = Math.max(0, INVENTORY_SIZE_PX - (heartSize * 2));

        String[] spriteOn = spriteList.getSprite(SpriteLoader.SPRITES.HEART).getSprite(Heart.HeartState.ON).split("\n");
        String[] spriteOff = spriteList.getSprite(SpriteLoader.SPRITES.HEART).getSprite(Heart.HeartState.OFF)
                .split("\n");

        String[] hungerSpriteOn = spriteList.getSprite(SpriteLoader.SPRITES.HUNGER).getSprite(Hunger.HungerState.ON)
                .split("\n");
        String[] hungerSpriteOff = spriteList.getSprite(SpriteLoader.SPRITES.HUNGER).getSprite(Hunger.HungerState.OFF)
                .split("\n");

        for (int i = 0; i < 9; i++) {
            buffer.append(" ".repeat(startLeft));
            for (int j = 0; j < 10; j++) {
                if (j < game.getPlayer().getHealth()) {
                    buffer.append(spriteOn[i]);
                } else {
                    buffer.append(spriteOff[i]);
                }
            }

            buffer.append("\033[0m").append(" ".repeat(moveLeft));
            for (int j = 0; j < 10; j++) {
                if ((10 - j) <= game.getPlayer().getHunger()) {
                    buffer.append(hungerSpriteOn[i]);
                } else {
                    buffer.append(hungerSpriteOff[i]);
                }
            }

            buffer.append("\n");
        }
        buffer.append("\n\n");
    }
}
