#include "ProductionSection.h"

#include <algorithm>

#include <QVBoxLayout>

#include "BarRow.h"
#include "Building.h"
#include "SectionBox.h"

ProductionSection::ProductionSection(QWidget* parent)
    : QWidget(parent)
{
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    m_section = new SectionBox(tr("Production"), this);
    m_bar     = new BarRow(QString(), m_section);
    m_section->getContentLayout()->addWidget(m_bar);
    layout->addWidget(m_section);
}

void ProductionSection::setProduction(bool runsProduction, const Building& building,
                                      double durationSeconds, Tick currentTick)
{
    // Nothing selected to produce means no progress indicator at all
    // (REQ-UI-PRODUCTION-PROGRESS).
    if (!runsProduction)
    {
        hide();
        return;
    }
    show();

    // No running cycle, or none whose length is known: the bar is empty and reads idle.
    if (durationSeconds <= 0.0 || !building.production.has_value())
    {
        m_bar->setValue(0.0, tr("idle"));
        return;
    }

    const Tick cycleTicks = secondsToTicks(durationSeconds);
    const Tick elapsed = currentTick - (building.production->completesAt - cycleTicks);
    const Tick clamped = std::max(Tick(0), std::min(cycleTicks, elapsed));
    const int percent = static_cast<int>(clamped * 100 / cycleTicks);
    m_bar->setValue(static_cast<double>(clamped) / cycleTicks, tr("%1%").arg(percent));
}
