#pragma once
#include <QObject>
#include <QPointF>
#include <QString>

class QSocketNotifier;

// Reads the reMarkable stylus (Elan marker, /dev/input/event2) directly from
// evdev. The epaper Qt platform delivers finger touch (event3) but NOT the pen,
// so Chatter handles the stylus itself. Maps raw digitizer coordinates to screen
// pixels and emits stroke signals for the ink canvas. The eraser end of the
// Marker Plus arrives as BTN_TOOL_RUBBER.
class PenDevice : public QObject {
    Q_OBJECT
public:
    explicit PenDevice(int screenWidth, int screenHeight,
                       const QString &devicePath = QStringLiteral("/dev/input/event2"),
                       QObject *parent = nullptr);
    ~PenDevice() override;

    bool isOpen() const { return m_fd >= 0; }

signals:
    void strokeStart(QPointF pos);
    void strokeMove(QPointF pos, qreal pressure, qreal tiltX, qreal tiltY, bool eraser);
    void strokeEnd();

private:
    void readEvents();
    QPointF mapToScreen() const;

    int m_fd = -1;
    QSocketNotifier *m_notifier = nullptr;
    int m_screenW;
    int m_screenH;

    // Device axis ranges (filled from EVIOCGABS; defaults are the measured ones).
    int m_xMin = 0, m_xMax = 6760;
    int m_yMin = 0, m_yMax = 11960;
    int m_pMin = 0, m_pMax = 4096;

    // Orientation — flip these if a test stroke comes out mirrored/rotated.
    bool m_invertX = false;
    bool m_invertY = false;
    bool m_swapXY  = false;

    // Current sample state.
    int m_rawX = 0, m_rawY = 0, m_rawP = 0;
    int m_rawTiltX = 0, m_rawTiltY = 0; // ABS_TILT_X/Y, range +/-9000
    bool m_touching = false;
    bool m_eraser = false;
};
