#include "blackwindow.h"
#include <QColor>
#include <QGuiApplication>
#include <QPainter>
#include <QScreen>
#include <QTimer>
#include <QX11Info>
#include <QPaintEvent>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/Xlib.h>
#include <xcb/xcb.h>

BlackWindow::BlackWindow(QWidget *parent) : QWidget(parent)
{
    setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint
                   | Qt::X11BypassWindowManagerHint);

    setAttribute(Qt::WA_TranslucentBackground);

    setCursor(Qt::BlankCursor);
    //qApp->installNativeEventFilter(this);
    //installEventFilter(this);
}

void BlackWindow::paintEvent(QPaintEvent *event)
{
    for(auto screen : QGuiApplication::screens())
    {
        QPainter painter(this);
        QColor cor = "#000000";
        painter.setBrush(cor);
        painter.drawRect(screen->geometry());

    }
    return QWidget::paintEvent(event);
}

void BlackWindow::laterActivate()
{
    raise();
}

bool BlackWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::WindowDeactivate){
         QTimer::singleShot(50,this,SLOT(laterActivate()));
    }

    return false;
}

bool BlackWindow::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
        if (qstrcmp(eventType, "xcb_generic_event_t") != 0 || screensaverIsShow) {
            return false;
        }
        xcb_generic_event_t *event = reinterpret_cast<xcb_generic_event_t*>(message);
        const uint8_t responseType = event->response_type & ~0x80;
        if (responseType == XCB_CONFIGURE_NOTIFY) {
            xcb_configure_notify_event_t *xc = reinterpret_cast<xcb_configure_notify_event_t*>(event);
            if(xc->window == winId())
                return false;
            XWindowAttributes window_attributes;
            XGetWindowAttributes (QX11Info::display(), xc->window,&window_attributes);
            XClassHint ch;
            ch.res_name = NULL;
            ch.res_class = NULL;
            XGetClassHint (QX11Info::display(), xc->window, &ch);
            if(QString(ch.res_name) == "ukui-screensaver-dialog"){
        //        screensaverIsShow = true;
                return false;
            }

            laterActivate();
         }else if(responseType == XCB_MAP_NOTIFY){
            xcb_map_notify_event_t *xm = reinterpret_cast<xcb_map_notify_event_t*>(event);
            if(xm->window == winId())
                    return false;
            XWindowAttributes window_attributes;
            XGetWindowAttributes (QX11Info::display(), xm->window,&window_attributes);
            XClassHint ch;
            ch.res_name = NULL;
            ch.res_class = NULL;
            XGetClassHint (QX11Info::display(), xm->window, &ch);
            if(QString(ch.res_name) == "ukui-screensaver-dialog"){
          //      screensaverIsShow = true;
                return false;
            }
            laterActivate();
     }
        return false;
}
