#include "ShipContent.h"

#include <QVBoxLayout>

#include "EntityAdmin.h"
#include "GameConfig.h"
#include "HealthComponent.h"
#include "SelectedBehaviorComponent.h"
#include "SelectionNames.h"
#include "ShipIdentityComponent.h"
#include "ShipStatsCalculator.h"
#include "ShipStatsPanel.h"
#include "Simulation.h"
#include "ThreatCostCalculator.h"

ShipContent::ShipContent(const SelectionContext& context,
                         const SelectionRequest& request, QWidget* parent)
    : SelectionContent(context, std::nullopt, parent)
    , m_entity(request.actors.front())
{
    m_statsPanel = new ShipStatsPanel(context.config, this);
    getRuntimeLayout()->addWidget(m_statsPanel);

    EntityAdmin& admin = context.sim->getAdmin();
    if (admin.isValid(m_entity) && admin.hasAll<ShipIdentityComponent>(m_entity))
    {
        setIdentity(QPixmap(), tr("Ship: %1").arg(QString::fromStdString(
            admin.get<ShipIdentityComponent>(m_entity).schematicId)));
    }
}

void ShipContent::refreshRuntime()
{
    EntityAdmin& admin = getContext().sim->getAdmin();
    if (!admin.isValid(m_entity) || !admin.hasAll<HealthComponent>(m_entity))
    {
        // The ship died or despawned. GameWorldView prunes it from the selection and
        // re-emits (REQ-UI-ENTITY-CLICK-SELECT), which rebuilds the card; this only has
        // to avoid reading it in the meantime.
        return;
    }

    const HealthComponent& health = admin.get<HealthComponent>(m_entity);
    if (health.hp <= 0.0f)
    {
        return;
    }

    const ShipStats stats = buildShipStatsFromEntity(admin, m_entity);
    m_statsPanel->refreshFromLive(stats, health.hp);
    m_statsPanel->setDebugDrawEnabled(*getContext().debugDrawEnabled);

    // The behavior is the header's right slot rather than a stat row, so it reads as
    // what the ship is doing rather than as another number (REQ-UI-SHIP-BEHAVIOR).
    setSlot(QColor(), getBehaviorLabel(
        admin.get<SelectedBehaviorComponent>(m_entity).winner));

    const ShipIdentityComponent& identity = admin.get<ShipIdentityComponent>(m_entity);
    const ShipDef* schematicDef =
        getContext().config->ships.findShipDef(identity.schematicId);
    if (schematicDef)
    {
        m_statsPanel->setThreatCost(calculateShipThreatCost(
            getContext().config->threatCosts, *getContext().config,
            schematicDef->id, schematicDef->defaultModules));
    }
}
