#include "DebrisContent.h"

#include <QVBoxLayout>

#include "DebrisScrap.h"
#include "IconCaption.h"
#include "ItemIconCache.h"
#include "ItemTooltip.h"
#include "Simulation.h"
#include "StatRow.h"

DebrisContent::DebrisContent(const SelectionContext& context,
                             const SelectionRequest& request, QWidget* parent)
    : SelectionContent(context, std::nullopt, parent)
    , m_debris(request.debris)
    , m_scrapIcon(context.itemIcons->getInlineIcon(kScrapItemId, font()))
{
    // The row states the amount and the bare scrap icon, the icon standing in for the
    // word so the row spells out neither the item nor its unit -- the form the header bar
    // states the block stock in (REQ-UI-DEBRIS-PANEL, REQ-UI-ITEM-ICON,
    // REQ-UI-BLOCKS-ICON). Without an icon file the caption has to name the item again,
    // since nothing else on the row would.
    m_scrapRow = new StatRow(
        m_scrapIcon.isNull() ? tr("Scrap remaining") : tr("Remaining"), this);
    m_scrapRow->setValueIcon(m_scrapIcon);
    m_scrapRow->setValueEmphasized(true);
    // Scrap is an item like any other, so the value explains it -- for scrap, that it is
    // salvaged rather than made (REQ-UI-ITEM-VALUE-TOOLTIP, REQ-UI-ITEM-TOOLTIP).
    ItemTooltip::attachTo(m_scrapRow->getValueWidget(),
                          context.getItemTooltipContext(), kScrapItemId,
                          TooltipTrigger::Trigger::HoverAndClick);
    getRuntimeLayout()->addWidget(m_scrapRow);

    setIdentity(QPixmap(), tr("Debris"));
    if (m_debris.size() > 1)
    {
        setCountSlot(static_cast<int>(m_debris.size()));
    }
}

void DebrisContent::refreshRuntime()
{
    // The value falls as the debris is collected and as pieces despawn
    // (REQ-UI-DEBRIS-CLICK-SELECT), so it is re-summed rather than remembered. With
    // several pieces selected it is their sum (REQ-UI-SELECTION-AGGREGATE).
    m_scrapRow->setValue(QString::number(
        sumDebrisScrap(getContext().sim->getAdmin(), m_debris)));
}
