#include "window.h"
#include "registry.h"
#include "figure-draw.h"
#include "xdg-shell-client-protocol.h"
#include <wayland-client.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdatomic.h>

#include "registry.h"

static atomic_uint_fast64_t shm_counter = 0;

static int32_t alloc_shm(size_t size)
{
	char name[64];
	uint64_t id = atomic_fetch_add(&shm_counter, 1);
	snprintf(name, sizeof(name), "/wayland-shm-%d-%llu", getpid(), (unsigned long long)id);

	int32_t fd = shm_open(name, O_RDWR | O_CREAT, 0600);
	if (fd == -1)
		return fd;
	shm_unlink(name);
	if (ftruncate(fd, size) == -1)
	{
		close(fd);
		return -1;
	}
	return fd;
}

static void destroy_frame_callback(struct wayland_window *win)
{
	if (win->frame_callback)
	{
		wl_callback_destroy(win->frame_callback);
		win->frame_callback = NULL;
	}
}

static void resize_canvas(struct wayland_window *win)
{
	struct window_draw_info *draw_info = &win->draw_info;
	size_t stride = draw_info->width * 4;
	size_t size = stride * draw_info->height;
	int32_t fd = alloc_shm(size);
	if (fd == -1)
		return;

	if (win->buffer)
	{
		wl_buffer_destroy(win->buffer);
		win->buffer = NULL;
	}

	void *map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (map == MAP_FAILED)
	{
		close(fd);
		return;
	}
	struct wl_shm *shm = registry_get_shm();
	struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size);
	win->buffer = wl_shm_pool_create_buffer(pool, 0, draw_info->width, draw_info->height, stride, WL_SHM_FORMAT_ARGB8888);
	wl_shm_pool_destroy(pool);
	close(fd);

	draw_info->data = map;
}

static void resize_new(struct wayland_window *win, int32_t w, int32_t h)
{
	if (!w || !h)
		return;
	struct window_draw_info *draw_info = &win->draw_info;

	if (draw_info->width != w || draw_info->height != h)
	{
		if (draw_info->data)
		{
			munmap(draw_info->data, draw_info->width * draw_info->height * 4);
			draw_info->data = NULL;
		}
		draw_info->width = w;
		draw_info->height = h;
		resize_canvas(win);
	}
}

static void draw(struct wayland_window *win)
{
	struct window_draw_info *draw_info = &win->draw_info;

	size_t stride = draw_info->width * 4;
	size_t size = stride * draw_info->height;

	if (!draw_info->data || !win->buffer)
		return;

	// Залочиться, чтобы операции обновления позиции фигуры происходили атомарно
	pthread_mutex_lock(&draw_info->figure_mutex);
	struct figure_animation_info figure = draw_info->figure;

	uint32_t color;
	switch (figure.type)
	{
	case FIGURE_CIRCLE:
		color = 0xFFFF0000;
		break;
	case FIGURE_TRIANGLE:
		color = 0xFF00FF00;
		break;
	case FIGURE_SQUARE:
		color = 0xFF0000FF;
		break;

	default:
		break;
	}

	uint8_t *bytes = (uint8_t *)draw_info->data;
	for (int32_t y = 0; y < (int32_t)draw_info->height; ++y)
	{
		uint32_t *row = (uint32_t *)(bytes + y * stride);
		for (int32_t x = 0; x < (int32_t)draw_info->width; ++x)
			row[x] = 0xAA5F5F5F; /* background black */
	}

	/* Draw figure into buffer. border thickness in pixels = 3.0f */
	figure_draw(&win->draw_info, 3.0f, 0xFF000000, color);
	pthread_mutex_unlock(&draw_info->figure_mutex);


	wl_surface_attach(win->wl_surface, win->buffer, 0, 0);
	wl_surface_damage_buffer(win->wl_surface, 0, 0, draw_info->width, draw_info->height);
	wl_surface_commit(win->wl_surface);
}

static void xdg_surface_conf(void *data, struct xdg_surface *xdg_surface_local, uint32_t serial)
{
	xdg_surface_ack_configure(xdg_surface_local, serial);
	struct wayland_window *win = data;
	if (!win->draw_info.data)
		resize_canvas(win);

	draw(win);
}

static void xdg_toplevel_conf(void *data, struct xdg_toplevel *xdg_top, int32_t w, int32_t h, struct wl_array *states)
{
	(void)states;
	struct wayland_window *win = data;
	resize_new(win, w, h);
}

static void xdg_toplevel_cls(void *data, struct xdg_toplevel *xdg_top)
{
	struct wayland_window *win = data;
	(void)xdg_top;
	win->need_close = 1;
}

static void xdg_toplevel_bounds(void *data, struct xdg_toplevel *xdg_top, int32_t w, int32_t h)
{
	(void)data;
	(void)xdg_top;
	(void)w;
	(void)h;
}

static void xdg_toplevel_wm_caps(void *data, struct xdg_toplevel *xdg_top, struct wl_array *caps)
{
	(void)data;
	(void)xdg_top;
	(void)caps;
}

static struct wl_callback_listener callback_listener;
static void setup_frame_callback(struct wayland_window *win, struct wl_event_queue *queue)
{
	struct wl_callback *cb = wl_surface_frame(win->wl_surface);
	win->frame_callback = cb;
	if (cb && queue)
		wl_proxy_set_queue((struct wl_proxy *)cb, queue);
	wl_callback_add_listener(cb, &callback_listener, win);
}

static void frame_new(void *data, struct wl_callback *cb, uint32_t _)
{
	struct wayland_window *win = data;
	if (win->frame_callback == cb)
		win->frame_callback = NULL;
	wl_callback_destroy(cb);
	setup_frame_callback(win, win->queue);
	draw(win);
}

static struct wl_callback_listener callback_listener = {
	.done = frame_new};
static struct xdg_surface_listener surface_listener = {
	.configure = xdg_surface_conf};
static struct xdg_toplevel_listener top_listener = {
	.configure = xdg_toplevel_conf,
	.close = xdg_toplevel_cls,
	.configure_bounds = xdg_toplevel_bounds,
	.wm_capabilities = xdg_toplevel_wm_caps};

int window_init(struct wl_display *display, struct wl_event_queue *queue, struct wayland_window *win)
{
	static int id = 0;
	(void)display;
	struct wl_compositor *compositor = registry_get_compositor();
	struct wl_shm *shm = registry_get_shm();
	struct xdg_wm_base *wm = registry_get_xdg_wm_base();
	if (!compositor || !shm || !wm)
		return -1;

	win->wl_surface = wl_compositor_create_surface(compositor);
	win->queue = queue;
	if (win->wl_surface && queue)
		wl_proxy_set_queue((struct wl_proxy *)win->wl_surface, queue);

	setup_frame_callback(win, queue);

	win->xdg_surface = xdg_wm_base_get_xdg_surface(wm, win->wl_surface);
	if (win->xdg_surface && queue)
		wl_proxy_set_queue((struct wl_proxy *)win->xdg_surface, queue);
	xdg_surface_add_listener(win->xdg_surface, &surface_listener, win);

	win->xdg_toplevel = xdg_surface_get_toplevel(win->xdg_surface);
	if (win->xdg_toplevel && queue)
		wl_proxy_set_queue((struct wl_proxy *)win->xdg_toplevel, queue);

	xdg_toplevel_add_listener(win->xdg_toplevel, &top_listener, win);

	wl_surface_commit(win->wl_surface);

	struct window_draw_info *draw_info = &win->draw_info;

	/* Инициализация состояния */
	win->id = id++;
	draw_info->width = 400;
	draw_info->height = 250;
	draw_info->data = NULL;
	
	/* Default animation state */
	draw_info->figure.type = FIGURE_CIRCLE;
	draw_info->figure.position.x = 0.5f;
	draw_info->figure.position.y = 0.5f;
	draw_info->figure.velocity.x = 0.5f;
	draw_info->figure.velocity.y = 0.5f;
	draw_info->figure.angle = 0.0f;
	draw_info->figure.angular_velocity = 0.01; /* radians per frame */
	draw_info->figure.speed = 10; /* speed multiplier */
	draw_info->figure.radius = 25.0f; /* radius in pixels */

	win->buffer = NULL;
	win->frame_callback = NULL;
	win->need_close = 0;
	/* Мьютекс нужен для атомарного обращения к структуре фигуры */
	if (pthread_mutex_init(&win->draw_info.figure_mutex, NULL) != 0)
	{
		/* if mutex init failed — cleanup and return error */
		window_destroy(win);
		return -1;
	}

	xdg_toplevel_set_app_id(win->xdg_toplevel, "my-wayland-window");
	xdg_toplevel_set_title(win->xdg_toplevel, "Custom Title");

	return 0;
}

int window_should_close(struct wayland_window *win)
{
	return win->need_close;
}

void window_destroy(struct wayland_window *win)
{
	destroy_frame_callback(win);
	if (win->buffer)
		wl_buffer_destroy(win->buffer);
	if (win->xdg_toplevel)
		xdg_toplevel_destroy(win->xdg_toplevel);
	if (win->xdg_surface)
		xdg_surface_destroy(win->xdg_surface);
	if (win->wl_surface)
		wl_surface_destroy(win->wl_surface);
	if (win->draw_info.data)
		munmap(win->draw_info.data, win->draw_info.width * win->draw_info.height * 4);
	/* destroy mutex if initialized */
	pthread_mutex_destroy(&win->draw_info.figure_mutex);
}
