#include "ClearBeltControl.h"

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

#include "Building.h"
#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 stuck items"), this);
    layout->addWidget(button);

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

void ClearBeltControl::clearSelectedTiles() const
{
    std::vector<QPoint> tiles;
    for (BuildingId id : m_ids)
    {
        const Building* building = findBuilding(m_context.sim->getFactoryState(), id);
        if (building && isBeltSubsystemType(building->type))
        {
            for (const QPoint& cell : building->bodyCells)
            {
                tiles.push_back(cell);
            }
        }
    }
    if (tiles.empty())
    {
        return;
    }

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