#include "xwlclipboard.h"
#include "xwlsource.h"
extern "C"
{
#include "log.h"
}

#include <stdio.h>

#include <xcb/xfixes.h>

XwlClipboard::XwlClipboard(xcb_atom_t atom, xcb_window_t parent, const xcb_query_extension_reply_t *queryExtension, xcb_connection_t *xcbConn)
    : XwlSelection(atom, parent, queryExtension, xcbConn)
{
    const uint32_t clipboardValues[] = {XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_PROPERTY_CHANGE};
    xcb_create_window(xcbConn,
                      XCB_COPY_FROM_PARENT,
                      window(),
                      parent,
                      0, 0,
                      10, 10,
                      0,
                      XCB_WINDOW_CLASS_INPUT_OUTPUT,
                      XCB_COPY_FROM_PARENT,
                      XCB_CW_EVENT_MASK,
                      clipboardValues);
    xcb_flush(xcbConn);
}

XwlClipboard::~XwlClipboard()
{

}

void XwlClipboard::setClipData(ClipData *clipData)
{
    if (clipData == nullptr) {
        xcb_set_selection_owner(x11Connection(),
                                XCB_WINDOW_NONE,
                                atom(),
                                XCB_TIME_CURRENT_TIME);
        xcb_flush(x11Connection());
        deleteX11Source();
        return;
    }

    if (!createX11Source(nullptr))
        return;

    if (X11Source *source = x11Source()) {
        source->setClipData(clipData);
    } else {
        log_error("Could not create a source.\n");
    }
}

void XwlClipboard::doHandleXfixesNotify(xcb_xfixes_selection_notify_event_t *event)
{
    if (!createX11Source(event))
        return;

    if (X11Source *source = x11Source()) {
        source->getTargets();
        m_waitingForTargets = true;
    } else if (event) {
        log_error("Could not create a source from %d %d\n", event->response_type, event->owner);
    }
}

bool XwlClipboard::handleSelectionNotify(xcb_selection_notify_event_t *event)
{
    return XwlSelection::handleSelectionNotify(event);
}
