#include "XcbExtensionInterface.h"

#include "FileLogger.h"

// Header is c-like, uses explicit as a var
#define explicit explicit_
#include <xcb/xkb.h>
#undef explicit

void XcbExtensionInterface::initialize(xcb_connection_t* connection)
{
    xcb_prefetch_extension_data(connection, &xcb_xkb_id);

    const auto reply = xcb_get_extension_data(connection, &xcb_xkb_id);
    if (!reply || !reply->present)
    {
        MLOG_ERROR("XKB extension not found on server");
        return;
    }

    auto cookie = xcb_xkb_use_extension(connection, 1, 0);
    auto extension_reply = xcb_xkb_use_extension_reply(connection, cookie, nullptr);
    if (!extension_reply)
    {
        MLOG_ERROR("XKB extension not found on server");
        return;
    }
    if (!extension_reply->supported)
    {
        MLOG_ERROR("XKB extension version not found on server");
        return;
    }

    mXkbEventFlag = reply->first_event;
    mHasXkb = true;
}

bool XcbExtensionInterface::isXkBEvent(unsigned responseType) const
{
    return mHasXkb && mXkbEventFlag == responseType;
}
