#include "icon-text-button.h"

#include <QPainter>
#include <QPainterPath>
#include <QStyle>
#include <QStyleOptionButton>

IconTextButton::IconTextButton(QWidget* parent) : QPushButton(parent) {}
IconTextButton::IconTextButton(const QString& text, QWidget* parent) : QPushButton(text, parent) {}
IconTextButton::IconTextButton(const QIcon& icon, const QString& text, QWidget* parent)
    : QPushButton(icon, text, parent) {}

void IconTextButton::paintEvent(QPaintEvent* e) {
    Q_UNUSED(e);

    QStyleOptionButton opt;
    initStyleOption(&opt);

    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing, true);

    const QRectF r = rect().adjusted(0.5, 0.5, -0.5, -0.5);
    const qreal radius = r.height() / 2.0;
    QPainterPath clipPath;
    clipPath.addRoundedRect(r, radius, radius);
    p.setClipPath(clipPath);

    style()->drawControl(QStyle::CE_PushButtonBevel, &opt, &p, this);

    const QRect contentsRect = style()->subElementRect(QStyle::SE_PushButtonContents, &opt, this);

    QIcon::Mode mode = (opt.state & QStyle::State_Enabled) ? QIcon::Normal : QIcon::Disabled;
    if (mode == QIcon::Normal && (opt.state & QStyle::State_HasFocus))
        mode = QIcon::Active;
    QIcon::State state = (opt.state & QStyle::State_On) ? QIcon::On : QIcon::Off;

    const QSize isz = iconSize().isValid() ? iconSize() : QSize(16, 16);
    const QPixmap pm = icon().pixmap(isz, mode, state);

    QRect iconRect = contentsRect;
    QRect textRect = contentsRect;

    if (!pm.isNull()) {
        iconRect.setWidth(isz.width());
        iconRect.setY(contentsRect.y() + (contentsRect.height() - isz.height()) / 2);
        iconRect.setHeight(isz.height());

        textRect.setLeft(iconRect.right() + m_gap);
    }

    if (!pm.isNull()) {
        style()->drawItemPixmap(&p, iconRect, Qt::AlignLeft | Qt::AlignVCenter, pm);
    }

    const int textFlags = Qt::AlignVCenter | Qt::AlignLeft | Qt::TextShowMnemonic;
    style()->drawItemText(&p, textRect, textFlags, opt.palette,
                          opt.state & QStyle::State_Enabled, opt.text, QPalette::ButtonText);
}
