#include "buttongadget.h"
using Xybrid::UI::ButtonGadget;

#include <QPainter>
#include <QFontMetricsF>
#include <QStyleOptionGraphicsItem>
#include <QGraphicsSceneMouseEvent>
#include <QCursor>

#include <QMenu>

namespace {
    const QFont font("Arcon Rounded", 8);
}

ButtonGadget::ButtonGadget(QGraphicsItem *parent) : Gadget(parent) {
    setAcceptHoverEvents(true);
}

QRectF ButtonGadget::boundingRect() const {
    return QRectF(QPointF(0, 0), size);
}

void ButtonGadget::paint(QPainter* p, const QStyleOptionGraphicsItem* opt, QWidget*) {
    auto r = boundingRect();
    //p->fillRect(rect, QColor(255, 0, 0));

    bool hover = opt->state & QStyle::State_MouseOver;

    QColor outline = QColor(31, 31, 31);

    QLinearGradient fill(r.topLeft(), r.bottomLeft());
    if (pressed) {
        fill.setColorAt(0.0, QColor(35, 35, 35));
        fill.setColorAt(1.0, QColor(47, 47, 47));
    } else {
        fill.setColorAt(0.0, QColor(63, 63, 63));
        if (hover) fill.setColorAt(0.32, QColor(71, 71, 71));
        fill.setColorAt(1.0, QColor(35, 35, 35));
    }

    p->setRenderHint(QPainter::RenderHint::Antialiasing);
    p->setBrush(QBrush(fill));
    p->setPen(QPen(QBrush(outline), 2));
    p->drawRoundedRect(r, 5, 5);

    if (!text.isEmpty()) {
        p->setFont(font);
        p->setBrush(QBrush(Qt::NoBrush));
        p->setPen(QColor(255, 255, 255));
        QFontMetricsF f(font);
        auto t = f.elidedText(text, Qt::ElideRight, static_cast<int>(r.width() - 8));
        p->drawText(QPointF(r.center().x() - f.width(t)/2, r.center().y() + f.ascent()/2), t);
    }
}

void ButtonGadget::mousePressEvent(QGraphicsSceneMouseEvent* e) {
    if (e->button() == Qt::LeftButton) {
        pressed = true;
        update();
    }
}
void ButtonGadget::mouseReleaseEvent(QGraphicsSceneMouseEvent* e) {
    if (e->button() == Qt::LeftButton) {
        if (pressed) emit clicked();
        pressed = false;
        update();
    }
}

void ButtonGadget::hoverEnterEvent(QGraphicsSceneHoverEvent*) { update(); }
void ButtonGadget::hoverLeaveEvent(QGraphicsSceneHoverEvent*) { pressed = false; update(); }
