#include "StatRow.h"

#include <QHBoxLayout>
#include <QLabel>
#include <QPalette>

#include "IconCaption.h"

namespace
{

// Left inset of an indented row, in device-independent pixels.
const int kIndentPx = 12;

}  // namespace


StatRow::StatRow(const QString& label, QWidget* parent)
    : QWidget(parent)
    , m_valueEmphasized(false)
{
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(8);

    m_labelLabel = new QLabel(label, this);
    m_valueLabel = new QLabel(this);
    m_valueLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    layout->addWidget(m_labelLabel);
    layout->addStretch(1);
    layout->addWidget(m_valueLabel);
}

void StatRow::setLabel(const QString& label)
{
    m_labelLabel->setText(label);
}

void StatRow::setValue(const QString& value)
{
    m_value = value;
    updateValue();
}

void StatRow::setValueIcon(const QPixmap& icon)
{
    m_valueIcon = icon;
    updateValue();
}

void StatRow::setValueEmphasized(bool emphasized)
{
    m_valueEmphasized = emphasized;

    QPalette valuePalette = m_valueLabel->palette();
    valuePalette.setColor(QPalette::WindowText, getValueColor());
    m_valueLabel->setPalette(valuePalette);

    updateValue();
}

void StatRow::setIndented(bool indented)
{
    layout()->setContentsMargins(indented ? kIndentPx : 0, 0, 0, 0);
}

QWidget& StatRow::getValueWidget()
{
    return *m_valueLabel;
}

void StatRow::updateValue()
{
    if (m_valueIcon.isNull())
    {
        m_valueLabel->setText(m_value);
        return;
    }
    // A label shows either text or a pixmap, so the two are composed into one -- the same
    // way the header bar states the block stock (REQ-UI-BLOCKS-ICON). The color is passed
    // in rather than left to the palette, which a pixmap does not follow.
    m_valueLabel->setPixmap(renderCaptionWithIcon(m_value, m_valueIcon,
                                                  m_valueLabel->font(), getValueColor()));
}

QColor StatRow::getValueColor() const
{
    return palette().color(m_valueEmphasized ? QPalette::Highlight
                                             : QPalette::WindowText);
}
