#include <object/ui/uibutton.hpp>

namespace Game::Object {
    UIButton::UIButton(const std::string& name, std::shared_ptr<Renderer::Texture> texture, const Transform& transform, void* clickFunction, float x, float y)
        : Entity(name, texture, transform), mClickFunction(clickFunction), mX(x), mY(y) { }

    void UIButton::start() {
        // Center the button on the requested position
        mTransform.x = mX - mTex->getWidth() * mTransform.adjustedScaleX() / 2.f;
        mTransform.y = mY - mTex->getHeight() * mTransform.adjustedScaleY() / 2.f;
    }

    void UIButton::update(float deltaTime) {
        if (!mIsActive) return;
        float mouseX = Input::getMouseX();
        float mouseY = Input::getMouseY();
        float textLeft = mTransform.x;
        float textRight = mTransform.x + mTex->getWidth() * mTransform.adjustedScaleX();
        float textTop = mTransform.y;
        float textBottom = mTransform.y + mTex->getHeight() * mTransform.adjustedScaleY();

        if (mouseX >= textLeft && mouseX <= textRight && mouseY >= textTop && mouseY <= textBottom) {
            std::dynamic_pointer_cast<Renderer::Font>(mTex)->build({200, 200, 200, 255}, mText); // Darken text when hovered
            if (Input::isMouseButtonJustPressed(SDL_BUTTON_LEFT) && mClickFunction) {
                using ClickFnType = void(*)();
                ClickFnType clickFn = reinterpret_cast<ClickFnType>(mClickFunction);
                clickFn();   
            }   
        }
        
    }

    void UIButton::setText(const std::string& text) {
        mText = text;
        std::dynamic_pointer_cast<Renderer::Font>(mTex)->build({255, 255, 255, 255}, text);
    }

    std::string UIButton::getText() const {
        return mText;
    }
}