#include "xeventmonitor.h"

#include <QDebug>

#include <X11/Xlib.h>
#include <X11/extensions/record.h>
#include <X11/Xlibint.h>
#include <X11/keysym.h>
#include <X11/XKBlib.h>

#define MAX_OPENDISPLAY_COUNT 10

UOSAI_BEGIN_NAMESPACE

class xEventMonitorPrivate
{
public:
    static void callback(XPointer trash, XRecordInterceptData* data);
    void handleRecordEvent(XRecordInterceptData *);
    XRecordContext m_context;
    Display *m_displayDatalink = nullptr;
    Display *keyPressDisplay = nullptr;
    xEventMonitor *q;
};

UOSAI_END_NAMESPACE

UOSAI_USE_NAMESPACE

xEventMonitor::xEventMonitor(QObject *parent) : BaseMonitor(parent)
{
    d = new xEventMonitorPrivate;
    d->q = this;
    start(QThread::LowestPriority);
}

void xEventMonitor::run()
{
    int count = 0;
    while (!isOpenDisplay) {
        if(MAX_OPENDISPLAY_COUNT <= count) {
            qInfo() << "unable to open display and opendisplay is 10 timesd\n";
            break;
        }

        msleep(500 * count);
        ++count;

        // Receive from ALL clients, including future clients.
        XRecordClientSpec clients = XRecordAllClients;
        XRecordRange* range = XRecordAllocRange();
        if (range == nullptr) {
            qWarning() <<"unable to allocate XRecordRange\n";
            continue;
        }

        // Receive KeyPress, KeyRelease, ButtonPress, ButtonRelease and MotionNotify events.
        memset(range, 0, sizeof(XRecordRange));
        range->device_events.first = KeyPress;
        range->device_events.last  = ButtonRelease;

        d->m_displayDatalink = XOpenDisplay(nullptr);

        if (d->m_displayDatalink == nullptr) {
            qWarning() << "unable to open second display\n";
            XFree(range);
            continue;
        }

        // And create the XRECORD context.
        d->m_context = XRecordCreateContext(d->m_displayDatalink, 0, &clients, 1, &range, 1);
        if (d->m_context == 0) {
            qWarning() <<"XRecordCreateContext failed\n";
            XFree(range);
            XCloseDisplay(d->m_displayDatalink);
            continue;
        }

        if (!XRecordEnableContext(d->m_displayDatalink, d->m_context, d->callback, (XPointer) this)) {
            qWarning() << "XRecordEnableContext() failed\n";
            XRecordFreeContext(d->m_displayDatalink, d->m_context);
            XFree(range);
            XCloseDisplay(d->m_displayDatalink);
            continue;
        }

        isOpenDisplay = true;
        XRecordFreeContext(d->m_displayDatalink, d->m_context);
        XFree(range);
        XCloseDisplay(d->m_displayDatalink);
        XCloseDisplay(d->keyPressDisplay);
    }
    qInfo() << "return";
    return;
}

void xEventMonitorPrivate::callback(XPointer ptr, XRecordInterceptData *data)
{
    ((xEventMonitor *) ptr)->d->handleRecordEvent(data);
    return;
}

void xEventMonitorPrivate::handleRecordEvent(XRecordInterceptData *data)
{
    if (data->category == XRecordFromServer) {
        xEvent *event = (xEvent *)data->data;
        switch (event->u.u.type) {
        case ButtonPress:
            emit q->mousePress(event->u.keyButtonPointer.rootX, event->u.keyButtonPointer.rootY);
            break;
        case ButtonRelease:
            emit q->mouseRelease(event->u.keyButtonPointer.rootX, event->u.keyButtonPointer.rootY);
            break;
        case KeyPress: {
            if (!keyPressDisplay) {
                keyPressDisplay = XOpenDisplay(nullptr);
                if (!keyPressDisplay) {
                    qWarning() << "unable to open keyPress display\n";
                    break;
                }
            }
            KeySym key = XKeycodeToKeysym(keyPressDisplay, event->u.u.detail, 0);
            if (key == XK_Escape)
                emit q->keyEscapePress();
            break;
        }
        default:
            break;
        }
    }
    XRecordFreeData(data);
    return;
}

bool xEventMonitor::isWheelEvent(int detail)
{
    //滚轮判断
    return !(detail != WheelUp && detail != WheelDown && detail != WheelLeft && detail != WheelRight);
}

