#include "registry.h"
#include "input.h"
#include <stdio.h>
#include <string.h>
#include <wayland-client.h>
#include "xdg-shell-client-protocol.h"

static struct wl_compositor *compositor = NULL;
static struct xdg_wm_base *xdg_wm_base = NULL;
static struct wl_shm *shm = NULL;

static void registry_global(void *data, struct wl_registry *reg, uint32_t name, const char *intf, uint32_t version)
{
    printf("%u\t%s\tv:%u\n", name, intf, version);
    if (!strcmp(intf, wl_compositor_interface.name))
    {
        compositor = wl_registry_bind(reg, name, &wl_compositor_interface, version);
    }
    else if (!strcmp(intf, wl_shm_interface.name))
    {
        shm = wl_registry_bind(reg, name, &wl_shm_interface, version);
    }
    else if (!strcmp(intf, xdg_wm_base_interface.name))
    {
        xdg_wm_base = wl_registry_bind(reg, name, &xdg_wm_base_interface, version);
        xdg_wm_base_add_listener(xdg_wm_base, NULL, NULL); /* will be set by window module if needed */
    }
    else if (!strcmp(intf, wl_seat_interface.name))
    {
        struct wl_seat *seat = wl_registry_bind(reg, name, &wl_seat_interface, version);
        /* Hook seat into input handler */
        input_register_seat(seat);
    }
}

static void registry_global_remove(void *data, struct wl_registry *reg, uint32_t name)
{
}

static const struct wl_registry_listener registry_listener = {
    .global = registry_global,
    .global_remove = registry_global_remove
};

void registry_add_listener(struct wl_registry *registry)
{
    wl_registry_add_listener(registry, &registry_listener, NULL);
}

struct wl_compositor *registry_get_compositor(void)
{
    return compositor;
}

struct wl_shm *registry_get_shm(void)
{
    return shm;
}

struct xdg_wm_base *registry_get_xdg_wm_base(void)
{
    return xdg_wm_base;
}
