#include "hidreader.h"
#include <QDebug>

HIDReader::HIDReader(QObject *parent)
    : QThread(parent), quit(false), device(nullptr) {
}

HIDReader::~HIDReader() {
    stopReading();
    wait();
    if (device) {
        hid_close(device);
    }
    hid_exit();
}

void HIDReader::startReading() {
    QMutexLocker locker(&mutex);
    if (!isRunning()) {
        start();
    } else {
        condition.wakeOne();
    }
}

void HIDReader::stopReading() {
    QMutexLocker locker(&mutex);
    quit = true;
    condition.wakeOne();
}


void HIDReader::run() {
    qDebug() << "Initializing HID...";
    if (hid_init() != 0) {
        qWarning() << "Failed to initialize HID library";
        return;
    }

    qDebug() << "Opening HID device...";
    device = hid_open(0x046a, 0x00cb, nullptr);
    if (!device) {
        qWarning() << "Unable to open device";
        return;
    }
    qDebug() << "HID device opened successfully";

    while (!quit) {
        unsigned char buf[256];
        qDebug() << "Reading from HID device...";
        int res = hid_read(device, buf, sizeof(buf));
        if (res > 0) {
            qDebug() << "Data read from HID device:" << QByteArray(reinterpret_cast<char*>(buf), res).toHex();
            QByteArray data(reinterpret_cast<char*>(buf), res);
            emit dataRead(data);
        } else if (res < 0) {
            const wchar_t* error = hid_error(device);
            if (error) {
                qWarning() << "Error reading from HID device:" << QString::fromWCharArray(error);
            } else {
                qWarning() << "Unknown error reading from HID device";
            }
            break;
        } else {
            qDebug() << "No data read from HID device";
        }
    }

    qDebug() << "Closing HID device...";
    hid_close(device);
    device = nullptr;
    qDebug() << "HID device closed";
}
