#include <game/agame/hudtext.hpp>
#include <game/gamemanager.hpp>
#include <window/window.hpp>
#include <sstream>

namespace Game::AGame {
    void HUDText::start() {
        mZIndex = 1000;
        Object::UIText::start();
        setText("Level 1 | Score 0 | Trash 0 | Polluters 0");
    }

    void HUDText::update(float deltaTime) {
        (void)deltaTime;

        int windowW = 0;
        int windowH = 0;
        SDL_GetWindowSizeInPixels(Window::Window::getSDLWindowBackend(), &windowW, &windowH);
        float camX = 0.f;
        float camY = 0.f;
        Object::Camera::getInstance().getPosition(camX, camY);

        auto anchorTopRight = [&]() {
            if (!mTex) {
                return;
            }

            const float marginX = 24.f;
            const float marginY = 24.f;
            const float textWidth = mTex->getWidth() * mTransform.adjustedScaleX();
            mTransform.x = camX + windowW / 2.f - marginX - textWidth;
            mTransform.y = camY - windowH / 2.f + marginY;
        };

        if (GameManager::getSharedData<bool>("gameLost")) {
            setText("Umrl si!");
            anchorTopRight();
            return;
        }

        if (GameManager::getSharedData<bool>("gameWon")) {
            setText("Zmagal si!");
            anchorTopRight();
            return;
        }

         const std::string playerName = GameManager::getSharedData<std::string>("playerName");

         std::stringstream stream;
         stream << "Igralec: " << (playerName.empty() ? std::string("Anonimni") : playerName)
             << " | Level " << GameManager::getSharedData<int>("gameStage")
             << " | Točke " << GameManager::getSharedData<int>("gameScore")
             << " | Smeti " << GameManager::getSharedData<int>("trashActiveCount")
             << " | Sovražniki " << GameManager::getSharedData<int>("enemyActiveCount");

         setText(stream.str());
        anchorTopRight();
    }
}
