#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <stdio.h>

int main(int argc, char **argv)
{
    Display *display = XOpenDisplay(NULL);
    if (!display) {
        fprintf(stderr, "Cannot connect to display\n");
        return 1;
    }

    int screenNumber = DefaultScreen(display);
    Window rootWindow = RootWindow(display, screenNumber);
    int depth = DefaultDepth(display, screenNumber);
    Visual *visual = DefaultVisual(display, screenNumber);
    Colormap colormap = DefaultColormap(display, screenNumber);

    // create a window at a certain position
    XSetWindowAttributes attrib;
    unsigned long mask = CWEventMask | CWBackPixel;
    attrib.event_mask = StructureNotifyMask;
    attrib.background_pixel = WhitePixel(display, screenNumber);

    Window window = XCreateWindow(display, rootWindow, 100, 100, 300, 200, 0,
                                  depth, InputOutput, visual, mask, &attrib);

    XSizeHints sizehint;
    sizehint.flags = USPosition;
    XSetWMNormalHints(display, window, &sizehint);

    XStoreName(display, window, "Initial Position: 100,100");
    XMapWindow(display, window);

    bool mapped = false;
    XConfigureEvent lastConfigureNotify;
    lastConfigureNotify.x = lastConfigureNotify.y = ~0;

    for (;;) {
        XEvent event;
        XNextEvent(display, &event);

        switch (event.type) {
        case ConfigureNotify:
            lastConfigureNotify = event.xconfigure;
            if (mapped) {
                printf("ConfigureNotify after being mapped, pos %d,%d\n",
                       lastConfigureNotify.x, lastConfigureNotify.y);
            } else if (lastConfigureNotify.send_event) {
                printf("got synthetic ConfigureNotify before being mapped, pos %d,%d\n",
                       lastConfigureNotify.x, lastConfigureNotify.y);
            }
            break;
        case MapNotify:
            printf("got MapNotify, last ConfigureNotify pos was %d,%d\n",
                   lastConfigureNotify.x, lastConfigureNotify.y);
            int root_x, root_y;
            Window unused;
            XTranslateCoordinates(display, window, rootWindow, 0, 0, &root_x, &root_y, &unused);
            printf("XTranslateCoordinates says pos is %d,%d\n", root_x, root_y);
            mapped = true;
            break;
        default:
            break;
        }
    }

    return 0;
}
