#include "ClearBeltControl.h"

#include <QPoint>
#include <QPushButton>
#include <QVBoxLayout>

#include "Command.h"
#include "CommandRequestedEvent.h"
#include "EventManager.h"
#include "FactoryQueries.h"
#include "Simulation.h"

ClearBeltControl::ClearBeltControl(const SelectionContext& context,
                                   const std::vector<BuildingId>& ids, QWidget* parent)
    : QWidget(parent)
    , m_context(context)
    , m_ids(ids)
{
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    QPushButton* button = new QPushButton(tr("Clear items"), this);
    layout->addWidget(button);

    connect(button, &QPushButton::clicked, this, [this]() { clearSelectedTiles(); });
}

void ClearBeltControl::clearSelectedTiles() const
{
    // The same tiles the item list above states the contents of (REQ-UI-BELT-ITEMS), so
    // the button cannot act on more or less than what the player was shown.
    const std::vector<QPoint> tiles =
        collectBeltTiles(m_context.sim->getFactoryState(), m_ids);
    if (tiles.empty())
    {
        return;
    }

    std::shared_ptr<ClearBeltTilesCommand> command =
        std::make_shared<ClearBeltTilesCommand>();
    command->tiles = tiles;
    EventManager::getInstance()->sendEventImmediately(
        std::make_shared<CommandRequestedEvent>(command));
}
