#include <DangerousRacers/Button.h>

#include "SFML/Window/Event.hpp"

constexpr int BUTTON_X_PADDING = 48, BUTTON_Y_PADDING = 32;

Button::Button(const std::string &labelString, const sf::Vector2f position, const std::function<void()>& _onClick) :
label("", {0,0}, true, false), onClick(_onClick) {
    label.setText(labelString);
    label.setPosition(position);

    // label.setColor({0, 0, 0});

    const sf::FloatRect bounds = label.getBounds();
    buttonRect.setSize({bounds.width + BUTTON_X_PADDING, bounds.height + BUTTON_Y_PADDING});
    buttonRect.setOrigin(bounds.width / 2.f + (BUTTON_X_PADDING / 2), bounds.height / 2.f - 14 + (BUTTON_Y_PADDING / 2));
    buttonRect.setPosition(position);
    buttonRect.setFillColor({0, 0, 0, 64});
}

void Button::setText(const std::string &labelString) {
    label.setText(labelString);
}

void Button::render(sf::RenderWindow &window) const {
    window.draw(buttonRect);
    label.render(window);
}

void Button::update(const float deltaTime) {

}

void Button::eventHandler(const sf::Event &event) {
    if (event.type == sf::Event::MouseMoved) {
        if (buttonRect.getGlobalBounds().contains(event.mouseMove.x, event.mouseMove.y)) {
            setSelected(true);
        } else setSelected(false);
    }

    if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left && selected) {
        // Trigger Button
        onClick();
    }
}