/*
 * Copyright (C) 2020, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "xeventmonitor.h"

#define MAX_OPENDISPLAY_COUNT 10

#define Bool int
#define Status int
#define True 1
#define False 0

xEventMonitor::xEventMonitor(QObject *parent) : QThread(parent)
{
    start(QThread::LowestPriority);
}

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

        msleep(500 * count);
        ++count;

        Display* display = QX11Info::display();
        if (display == NULL) {
            printf( "unable to open display\n");
            continue;
        }

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

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

        // And create the XRECORD context.
        m_context = XRecordCreateContext(display, 0, &clients, 1, &range, 1);
        if (m_context == NULL) {
            printf("XRecordCreateContext failed\n");
            XFree(range);
            continue;
        }
        XFree(range);
        XSync(display, True);

        m_displayDatalink = XOpenDisplay(NULL);
        if (m_displayDatalink == NULL) {
            printf("unable to open second display\n");
            continue;
        }

        if (!XRecordEnableContext(m_displayDatalink, m_context, callback, (XPointer) this)) {
            printf("XRecordEnableContext() failed\n");
            XCloseDisplay(m_displayDatalink);
            continue;
        }

        isOpenDisplay = true;
        XCloseDisplay(m_displayDatalink);
    }

    return;
}

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

    return;
}

void xEventMonitor::freeXres()
{
    XRecordDisableContext(QX11Info::display(), m_context);
    XRecordFreeContext(QX11Info::display(), m_context);
    XSync(QX11Info::display(), True);

    return;
}

void xEventMonitor::handleRecordEvent(XRecordInterceptData *data)
{
    if (data->category == XRecordFromServer) {
        xEvent *event = (xEvent *)data->data;

        switch (event->u.u.type) {
        case ButtonPress:
            if (!isWheelEvent(event->u.u.detail)) {

                Q_EMIT mousePress(event->u.keyButtonPointer.rootX, event->u.keyButtonPointer.rootY);
            }

            break;
        case ButtonRelease:
            if (!isWheelEvent(event->u.u.detail)) {

                Q_EMIT mouseRelease(event->u.keyButtonPointer.rootX, event->u.keyButtonPointer.rootY);
            }

            break;

        default:
            break;
        }
    }

    XRecordFreeData(data);
    return;
}

bool xEventMonitor::isWheelEvent(int detail)
{
    return !(detail != WheelUp && detail != WheelDown && detail != WheelLeft && detail != WheelRight);
}

