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

#include "input.h"
#include "input-handle.h"
#include "wayland-runtime.h"
#include "window.h"

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

/* Обработчики клавиатуры */
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)
{
    /* Сохраняем поверхность, которая получила фокус клавиатуры */
    focused_window = get_window_by_surface(surface);
}

static void keyboard_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface)
{
    /* Если уходим с фокусной поверхности — сбросить фокус */
    if (focused_window && focused_window->wl_surface == surface)
        focused_window = NULL;
}

static void keyboard_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state)
{
    enum keyboard_key_state key_state = (state == WL_KEYBOARD_KEY_STATE_PRESSED) ? KEYBOARD_KEY_STATE_PRESSED
                    : (state == WL_KEYBOARD_KEY_STATE_REPEATED) ? KEYBOARD_KEY_STATE_REPEATED 
                    : KEYBOARD_KEY_STATE_RELEASED;

    if (xkb_state && focused_window)
    {
        xkb_keycode_t kc = (xkb_keycode_t)key + 8;
        xkb_keysym_t ks = xkb_state_key_get_one_sym(xkb_state, kc);
    
        keyboard_key_handle(kc, ks, key_state, focused_window);
    }
}

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)
{
    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)
{
}

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};

/* Обработчики wl_seat */
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;
    }
    focused_window = NULL;
}
