#include "DeliverScrapExecutor.h"
#include "FactoryQueries.h"

#include <QVector2D>

#include "BehaviorKind.h"
#include "Building.h"
#include "BuildingSystem.h"
#include "DeliverScrapBehavior.h"
#include "EntityAdmin.h"
#include "MovementIntentComponent.h"
#include "PositionComponent.h"
#include "SelectedBehaviorComponent.h"
#include "tracing.h"

void DeliverScrapExecutor::execute(EntityAdmin& admin, const FactoryState& state)
{
    TRACE();
    admin.forEach<DeliverScrapBehavior, SelectedBehaviorComponent, PositionComponent,
                  MovementIntentComponent>(
        [&](entt::entity /*e*/, const DeliverScrapBehavior& deliver,
            const SelectedBehaviorComponent& selected, const PositionComponent& pos,
            MovementIntentComponent& intent)
        {
            if (selected.winner != BehaviorKind::DeliverScrap) { return; }

            QVector2D dest = pos.value;
            if (deliver.deliveryBay.has_value())
            {
                const Building* bay = findBuilding(state, *deliver.deliveryBay);
                if (bay)
                {
                    dest = QVector2D(bay->anchor.x() + bay->footprint.width()  / 2.0f,
                                     bay->anchor.y() + bay->footprint.height() / 2.0f);
                }
            }
            intent = MovementIntentComponent{true, dest};
        });
}
