#include "selectorgadget.h"
using Xybrid::UI::SelectorGadget;

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

#include <QMenu>

SelectorGadget::SelectorGadget(QGraphicsItem *parent) : Gadget(parent) {
    setAcceptHoverEvents(true);

    font = QFont("Arcon Rounded", 8);
}

QRectF SelectorGadget::boundingRect() const {
    return QRectF(QPointF(0, 0), QSizeF(width, 24));
}

void SelectorGadget::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);
    if (hover) outline = QColor(127, 127, 255);

    QLinearGradient fill(r.topLeft(), r.bottomLeft());
    fill.setColorAt(0.0, QColor(95, 95, 95));
    fill.setColorAt(0.32, QColor(63, 63, 63));
    //fill.setColorAt(1.0 - (1.0 - 8.0/r.height()) / 2, QColor(55, 55, 55));
    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, 8, 8);

    p->setPen(QPen(Qt::NoPen));
    p->setBrush(outline);
    qreal tw = 6;
    QPointF tc = {r.right() - 4 - tw/2, r.center().y()};
    p->drawPolygon(QPolygonF({tc + QPointF(-tw/2, -tw/2), tc + QPointF(tw/2, -tw/2), tc + QPointF(0, tw/2)}));

    p->setFont(font);
    p->setBrush(QBrush(Qt::NoBrush));
    p->setPen(QColor(255, 255, 255));
    QFontMetrics f(font);
    p->drawText(QPointF(r.left() + 4, r.center().y() + f.ascent()/2), f.elidedText(_entry.second, Qt::ElideRight, static_cast<int>(r.width() - 8-2-tw)));
}

void SelectorGadget::mousePressEvent(QGraphicsSceneMouseEvent* e) {
    if (e->button() == Qt::LeftButton) {
        auto* m = new QMenu();
        std::vector<Entry> v = fGetList ? fGetList() : std::vector<Entry>();
        if (v.empty()) m->addAction("(no entries)")->setDisabled(true);
        else {
            for (auto e : v) {
                if (_entry.first == e.first) {
                    m->addAction(e.second)->setDisabled(true);
                } else m->addAction(e.second, [this, e] {
                    setEntry(e);
                });
            }
        }
        if (fEditMenu) fEditMenu(m);
        m->setAttribute(Qt::WA_DeleteOnClose);
        m->popup(e->screenPos());
    }
}

void SelectorGadget::hoverEnterEvent(QGraphicsSceneHoverEvent*) { update(); }
void SelectorGadget::hoverLeaveEvent(QGraphicsSceneHoverEvent*) { update(); }
