#include "input.h"
#include <stdio.h>
#include <xkbcommon/xkbcommon.h>
#include <wayland-client.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>

static __thread struct wl_seat *seat = NULL;
static __thread struct wl_keyboard *keyboard = NULL;
static __thread struct xkb_context *xkb_ctx = NULL;
static __thread struct xkb_keymap *xkb_keymap = NULL;
static __thread struct xkb_state *xkb_state = NULL;

/* keyboard callbacks */
static void keyboard_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size)
{
    printf("keyboard: keymap format=%u size=%u\n", format, size);
    if (fd < 0)
        return;

    if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1)
    {
        close(fd);
        return;
    }

    char *map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
    if (map == MAP_FAILED)
    {
        perror("mmap");
        close(fd);
        return;
    }

    if (!xkb_ctx)
        xkb_ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);

    if (xkb_state)
    {
        xkb_state_unref(xkb_state);
        xkb_state = NULL;
    }
    if (xkb_keymap)
    {
        xkb_keymap_unref(xkb_keymap);
        xkb_keymap = NULL;
    }

    xkb_keymap = xkb_keymap_new_from_string(xkb_ctx, map, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
    if (!xkb_keymap)
    {
        fprintf(stderr, "Unable to compile xkb keymap\n");
        munmap(map, size);
        close(fd);
        return;
    }

    xkb_state = xkb_state_new(xkb_keymap);

    munmap(map, size);
    close(fd);
}

static void keyboard_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys)
{
    printf("keyboard: enter serial=%u surface=%p\n", serial, surface);
}

static void keyboard_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface)
{
    printf("keyboard: leave serial=%u surface=%p\n", serial, surface);
}

static void keyboard_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state)
{
    const char *s = (state == WL_KEYBOARD_KEY_STATE_PRESSED) ? "PRESSED" : "RELEASED";
    printf("keyboard: key serial=%u time=%u key=%u state=%s\n", serial, time, key, s);

    if (xkb_state)
    {
        xkb_keycode_t kc = (xkb_keycode_t)key + 8;
        xkb_keysym_t ks = xkb_state_key_get_one_sym(xkb_state, kc);
        if (ks != XKB_KEY_NoSymbol)
        {
            char buf[64];
            int n = xkb_keysym_to_utf8(ks, buf, sizeof(buf));
            if (n > 0)
                printf("keyboard: symbol '%s' (keysym 0x%x)\n", buf, ks);
            else
                printf("keyboard: keysym 0x%x (no UTF-8 representation)\n", ks);
        }
    }
}

static void keyboard_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group)
{
    printf("keyboard: modifiers serial=%u depressed=%u latched=%u locked=%u group=%u\n", serial, mods_depressed, mods_latched, mods_locked, group);
    if (xkb_state)
    {
        xkb_state_update_mask(xkb_state, mods_depressed, mods_latched, mods_locked, group, 0, 0);
    }
}

static void keyboard_repeat_info(void *data, struct wl_keyboard *keyboard, int32_t rate, int32_t delay)
{
    printf("keyboard: repeat rate=%d delay=%d\n", rate, delay);
}

static const struct wl_keyboard_listener keyboard_listener = {
    .keymap = keyboard_keymap,
    .enter = keyboard_enter,
    .leave = keyboard_leave,
    .key = keyboard_key,
    .modifiers = keyboard_modifiers,
    .repeat_info = keyboard_repeat_info
};

/* seat callbacks */
static void seat_capabilities(void *data, struct wl_seat *seat_local, uint32_t caps)
{
    if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !keyboard)
    {
        keyboard = wl_seat_get_keyboard(seat_local);
        wl_keyboard_add_listener(keyboard, &keyboard_listener, NULL);
        printf("Seat reports keyboard capability - keyboard bound\n");
    }
    else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && keyboard)
    {
        wl_keyboard_destroy(keyboard);
        keyboard = NULL;
        if (xkb_state)
        {
            xkb_state_unref(xkb_state);
            xkb_state = NULL;
        }
        if (xkb_keymap)
        {
            xkb_keymap_unref(xkb_keymap);
            xkb_keymap = NULL;
        }
    }
}

static void seat_name(void *data, struct wl_seat *seat, const char *name)
{
    printf("Seat name: %s\n", name);
}

static const struct wl_seat_listener seat_listener = {
    .capabilities = seat_capabilities,
    .name = seat_name
};

void input_register_seat(struct wl_seat *s)
{
    if (!s)
        return;
    if (seat)
    {
        if (keyboard)
        {
            wl_keyboard_destroy(keyboard);
            keyboard = NULL;
        }
        wl_seat_destroy(seat);
        seat = NULL;
    }
    seat = s;
    wl_seat_add_listener(seat, &seat_listener, NULL);
}

void input_cleanup(void)
{
    if (keyboard)
    {
        wl_keyboard_destroy(keyboard);
        keyboard = NULL;
    }
    if (seat)
    {
        wl_seat_destroy(seat);
        seat = NULL;
    }
    if (xkb_state)
    {
        xkb_state_unref(xkb_state);
        xkb_state = NULL;
    }
    if (xkb_keymap)
    {
        xkb_keymap_unref(xkb_keymap);
        xkb_keymap = NULL;
    }
    if (xkb_ctx)
    {
        xkb_context_unref(xkb_ctx);
        xkb_ctx = NULL;
    }
}
