#include <stdio.h>
#include <stdlib.h>

#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <X11/Xlib.h>

#include "util.h"

#define _NET_WM_STATE_REMOVE   0
#define _NET_WM_STATE_ADD      1
#define _NET_WM_STATE_TOGGLE   2

/*** Private Prototypes ***/

static void ewmh_set_state(GtkWidget* win, uint32 action, char* atom1, char* atom2);
static void client_msg(GtkWidget* win, char* msg, uint32 data0, uint32 data1,
                        uint32 data2, uint32 data3, uint32 data4);

/*** Public Functions ***/

void ewmh_toggle_fullscreen(GtkWidget* win)
{
    ewmh_set_state(win, _NET_WM_STATE_TOGGLE, "_NET_WM_STATE_FULLSCREEN", NULL);
}

/*** Private Functions ***/

static void ewmh_set_state(GtkWidget* win, uint32 action, char* atom1, char* atom2)
{
    client_msg(win, "_NET_WM_STATE", action,
               (uint32)(XInternAtom(GDK_DISPLAY(), atom1, FALSE)),
               (atom2 ? (uint32)(XInternAtom(GDK_DISPLAY(), atom2, FALSE)) : 0),
               0, 0);
}

static void client_msg(GtkWidget* win, char* msg, uint32 data0, uint32 data1,
                       uint32 data2, uint32 data3, uint32 data4) {
    XEvent event;
    int32 mask = SubstructureRedirectMask | SubstructureNotifyMask;

    event.xclient.type         = ClientMessage;
    event.xclient.serial       = 0;
    event.xclient.send_event   = TRUE;
    event.xclient.message_type = XInternAtom(GDK_DISPLAY(), msg, FALSE);
    event.xclient.window       = GDK_WINDOW_XWINDOW(win->window);
    event.xclient.format       = 32;
    event.xclient.data.l[0]    = data0;
    event.xclient.data.l[1]    = data1;
    event.xclient.data.l[2]    = data2;
    event.xclient.data.l[3]    = data3;
    event.xclient.data.l[4]    = data4;
    XSendEvent(GDK_DISPLAY(), GDK_ROOT_WINDOW(), FALSE, mask, &event);
}
