#ifndef GRAPHICSTEXTITEM_H
#define GRAPHICSTEXTITEM_H

#include "graphicsBaseItem.h"
#include "IPropertyGroupProvider.h"
#include "global.h"

#include <QGraphicsTextItem>
#include <QFont>

class GraphicsTextItem : public AbstractShapeType<QGraphicsTextItem>,
                         public IPropertyGroupProvider
{
    Q_OBJECT
    Q_PROPERTY(QString text READ toPlainText WRITE setPlainText)
    Q_PROPERTY(QPointF ptPosition READ pos WRITE setPos FINAL)
    Q_PROPERTY(QFont textFont READ textFont WRITE setTextFont)
    Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor)
    Q_PROPERTY(QColor backgroundColor READ brushColor WRITE setBrushColor)

public:
    explicit GraphicsTextItem(QGraphicsItem *parent = nullptr);
    virtual ~GraphicsTextItem();

    // IPropertyGroupProvider
    QString getPropertyGroup(const QString &propertyName) const override;

    // Override QGraphicsItem::type()
    enum { Type = GIT_text };
    int type() const override { return Type; }

    void resize(int nHandle, double dSX, double dSY, const QPointF &basePoint) override;
    void updateCoordinate() override;
    void move(const QPointF &pt) override;
    QJsonObject serialize() const override;
    static QGraphicsItem *createFromJson(const QJsonObject &obj);

    void createOperationCopy() override;
    void removeOperationCopy() override;
    void moveOperationCopy(const QPointF &) override;
    void rotateOperationCopy(const double &) override;
    void syncRotationDataFromParent(const double &) override;

    // Font property accessors
    QFont textFont() const { return font(); }
    void setTextFont(const QFont &f) { setFont(f); updateSizeFromText(); }

    // Text color accessor (foreground)
    QColor textColor() const { return defaultTextColor(); }
    void setTextColor(const QColor &c) { setDefaultTextColor(c); }

    // Editing mode (separate from selection)
    void startEditing();
    void endEditing();
    bool isEditing() const { return m_bEditing; }

protected:
    QPainterPath shape() override;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
    QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
    void focusOutEvent(QFocusEvent *event) override;
    void focusInEvent(QFocusEvent *event) override;

private:
    void updateHandles() override;
    void updateSizeFromText();

    QRectF m_lastBoundingRect;
    double  m_dLastPointSize = 14;
    bool    m_bEditing = false;
};

#endif // GRAPHICSTEXTITEM_H
