#include "RecipeSelectionControl.h"

#include <vector>

#include <QPushButton>
#include <QVBoxLayout>

#include "EventManager.h"
#include "RecipeSelectionDialog.h"
#include "RecipeSelectionRequestedEvent.h"
#include "Simulation.h"

RecipeSelectionControl::RecipeSelectionControl(const SelectionContext& context,
                                               BuildingId id, BuildingType type,
                                               QWidget* parent)
    : QWidget(parent)
    , m_context(context)
    , m_id(id)
    , m_type(type)
{
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    m_button = new QPushButton(this);
    layout->addWidget(m_button);

    connect(m_button, &QPushButton::clicked, this, [this]() {
        // Sent synchronously: MainWindow pauses the game, runs the modal dialog, and
        // restores the speed before this returns. The chosen recipe is only enqueued as
        // a command though, and drains on a later frame -- so the caption follows from
        // the next refresh, not from here.
        EventManager::getInstance()->sendEventImmediately(
            std::make_shared<RecipeSelectionRequestedEvent>(m_id));
    });
}

void RecipeSelectionControl::setRecipeId(const std::string& recipeId)
{
    const std::vector<RecipeSelectionOption> options =
        buildRecipeSelectionOptions(m_type, *m_context.sim, *m_context.config);

    for (const RecipeSelectionOption& option : options)
    {
        if (option.id == recipeId && !option.id.empty())
        {
            m_button->setText(option.caption);
            return;
        }
    }

    // No tooltip of its own: what the building has selected is drawn beneath the button
    // as the recipe summary, and where its items come from is reachable by hovering the
    // card's item chips (REQ-UI-SELECT-BUTTON, REQ-UI-ITEM-TOOLTIP).
    m_button->setText(m_type == BuildingType::Shipyard
        ? tr("Select schematic")
        : tr("Select recipe"));
}
