/*
 * What a list item or a canvas draws with (`g`), pictures, and input
 * events as tables.
 *
 * `g` is only good while the draw function runs: the cairo context
 * under it is the frame's. Colours are 0xRRGGBB numbers or "#rrggbb";
 * left out, the text colour of where it draws.
 */
#include <string.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <xkbcommon/xkbcommon.h>
#include "c8lua.h"

#define DRAW_META "c8.draw"
#define IMAGE_META "c8.picture"
#define GRADIENT_META "c8.gradient"

struct draw {
	cairo_t *cr; // NULL once the draw is over
	struct c8ui_widget *w;
};

struct picture {
	cairo_surface_t *surface;
};

struct gradient {
	cairo_pattern_t *pattern;
};

void c8l_draw_begin(lua_State *L, cairo_t *cr, struct c8ui_widget *w) {
	struct draw *d = lua_newuserdatauv(L, sizeof(*d), 0);
	d->cr = cr;
	d->w = w;
	luaL_setmetatable(L, DRAW_META);
}

void c8l_draw_end(lua_State *L, int index) {
	struct draw *d = luaL_testudata(L, index, DRAW_META);
	if (d) {
		d->cr = NULL;
		d->w = NULL;
	}
}

static struct draw *draw_at(lua_State *L) {
	struct draw *d = luaL_checkudata(L, 1, DRAW_META);
	if (d->cr == NULL) {
		luaL_error(L, "g can only draw while the draw function runs");
	}
	return d;
}

/* The colours where it draws; a picture being drawn (no widget) has
 * black on white */
static struct c8ui_colors colors_of(struct draw *d) {
	if (d->w) {
		return c8ui_widget_colors(d->w);
	}
	return (struct c8ui_colors){ .bg = 0xffffff, .fg = 0x000000,
		.accent = 0x1ba1e2, .fg_secondary = 0.6 };
}

/* The colour at index (or a gradient, c8.gradient) and the alpha after
 * it */
static void source(lua_State *L, struct draw *d, int index) {
	struct gradient *grad = luaL_testudata(L, index, GRADIENT_META);
	if (grad) {
		cairo_set_source(d->cr, grad->pattern);
		return;
	}
	struct c8ui_colors c = colors_of(d);
	c8ui_set_source(d->cr, c8l_color(L, index, c.fg),
		luaL_optnumber(L, index + 1, 1));
}

/* g:rect(x, y, width, height [, color [, alpha]]) */
static int g_rect(lua_State *L) {
	struct draw *d = draw_at(L);
	source(L, d, 6);
	cairo_rectangle(d->cr, luaL_checknumber(L, 2), luaL_checknumber(L, 3),
		luaL_checknumber(L, 4), luaL_checknumber(L, 5));
	cairo_fill(d->cr);
	return 0;
}

/* g:frame(x, y, width, height [, color [, alpha [, thickness]]]) */
static int g_frame(lua_State *L) {
	struct draw *d = draw_at(L);
	double t = luaL_optnumber(L, 8, 1);
	source(L, d, 6);
	cairo_set_line_width(d->cr, t);
	cairo_rectangle(d->cr, luaL_checknumber(L, 2) + t / 2,
		luaL_checknumber(L, 3) + t / 2, luaL_checknumber(L, 4) - t,
		luaL_checknumber(L, 5) - t);
	cairo_stroke(d->cr);
	return 0;
}

/* g:line(x1, y1, x2, y2 [, color [, alpha [, thickness]]]) */
static int g_line(lua_State *L) {
	struct draw *d = draw_at(L);
	source(L, d, 6);
	cairo_set_line_width(d->cr, luaL_optnumber(L, 8, 1));
	cairo_move_to(d->cr, luaL_checknumber(L, 2), luaL_checknumber(L, 3));
	cairo_line_to(d->cr, luaL_checknumber(L, 4), luaL_checknumber(L, 5));
	cairo_stroke(d->cr);
	return 0;
}

/* g:circle(cx, cy, radius [, color [, alpha]]) */
static int g_circle(lua_State *L) {
	struct draw *d = draw_at(L);
	source(L, d, 5);
	cairo_new_sub_path(d->cr);
	cairo_arc(d->cr, luaL_checknumber(L, 2), luaL_checknumber(L, 3),
		luaL_checknumber(L, 4), 0, 2 * G_PI);
	cairo_fill(d->cr);
	return 0;
}

/* g:shape({ x1, y1, x2, y2, ... } [, color [, alpha]]): a filled
 * polygon */
static int g_shape(lua_State *L) {
	struct draw *d = draw_at(L);
	luaL_checktype(L, 2, LUA_TTABLE);
	lua_Integer n = luaL_len(L, 2);
	for (lua_Integer i = 1; i + 1 <= n; i += 2) {
		lua_geti(L, 2, i);
		lua_geti(L, 2, i + 1);
		double x = lua_tonumber(L, -2), y = lua_tonumber(L, -1);
		lua_pop(L, 2);
		if (i == 1) {
			cairo_move_to(d->cr, x, y);
		} else {
			cairo_line_to(d->cr, x, y);
		}
	}
	cairo_close_path(d->cr);
	source(L, d, 3);
	cairo_fill(d->cr);
	return 0;
}

/* g:paint([color [, alpha]]): everything it draws on */
static int g_paint(lua_State *L) {
	struct draw *d = draw_at(L);
	source(L, d, 2);
	cairo_paint(d->cr);
	return 0;
}

static const char *const styles[] = { "header", "subheader", "title", "item",
	"body", "strong", "caption", NULL };
static const char *const weights[] = { "light", "semilight", "normal",
	"semibold", "bold", NULL };

/* The font the options table at index (may be absent) asks for */
static struct c8ui_font font_of(lua_State *L, int index) {
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	if (!lua_istable(L, index)) {
		return font;
	}
	const char *style = c8l_field_str(L, index, "style", NULL);
	for (int i = 0; style && styles[i]; i++) {
		if (strcmp(style, styles[i]) == 0) {
			font = c8ui_text_font(i);
		}
	}
	font.size = c8l_field_num(L, index, "size", font.size);
	const char *weight = c8l_field_str(L, index, "weight", NULL);
	for (int i = 0; weight && weights[i]; i++) {
		if (strcmp(weight, weights[i]) == 0) {
			font.weight = i;
		}
	}
	return font;
}

/* With baseline = true: y is where the letters stand, and cairo's own
 * simple text draws it (one line, no wrapping), family "sans-serif"
 * unless given. Returns the width. */
static int text_on_baseline(lua_State *L, struct draw *d, const char *text,
		struct c8ui_font font) {
	cairo_select_font_face(d->cr, c8l_field_str(L, 5, "family", "sans-serif"),
		CAIRO_FONT_SLANT_NORMAL, font.weight >= C8UI_WEIGHT_SEMIBOLD ?
		CAIRO_FONT_WEIGHT_BOLD : CAIRO_FONT_WEIGHT_NORMAL);
	cairo_set_font_size(d->cr, font.size);
	cairo_text_extents_t ext;
	cairo_text_extents(d->cr, text, &ext);
	cairo_move_to(d->cr, luaL_checknumber(L, 3), luaL_checknumber(L, 4));
	cairo_show_text(d->cr, text);
	cairo_new_path(d->cr);
	lua_pushnumber(L, ext.x_advance);
	return 1;
}

/* g:text(text, x, y [, { style, size, weight, family, color, alpha,
 * width, lines, baseline }]): returns the height it took */
static int g_text(lua_State *L) {
	struct draw *d = draw_at(L);
	const char *text = luaL_tolstring(L, 2, NULL);
	struct c8ui_colors c = colors_of(d);
	uint32_t rgb = c.fg;
	double alpha = 1, width = 0;
	int lines = 0;
	if (lua_istable(L, 5)) {
		lua_getfield(L, 5, "color");
		rgb = c8l_color(L, -1, c.fg);
		lua_pop(L, 1);
		alpha = c8l_field_num(L, 5, "alpha", 1);
		width = c8l_field_num(L, 5, "width", 0);
		lines = (int)c8l_field_num(L, 5, "lines", width > 0 ? 1 : 0);
	}
	c8ui_set_source(d->cr, rgb, alpha);
	if (lua_istable(L, 5) && c8l_field_bool(L, 5, "baseline", false)) {
		return text_on_baseline(L, d, text, font_of(L, 5));
	}
	const char *family = lua_istable(L, 5) ?
		c8l_field_str(L, 5, "family", NULL) : NULL;
	if (family == NULL && d->w) {
		family = c8ui_widget_font(d->w);
	}
	lua_pushnumber(L, c8ui_text_draw(d->cr, family, font_of(L, 5), text,
		luaL_checknumber(L, 3), luaL_checknumber(L, 4), width, lines));
	return 1;
}

/* g:measure(text [, { ... }]): width, height */
static int g_measure(lua_State *L) {
	struct draw *d = draw_at(L);
	const char *text = luaL_tolstring(L, 2, NULL);
	double width = 0, height = 0, max = 0;
	int lines = 0;
	if (lua_istable(L, 3)) {
		max = c8l_field_num(L, 3, "width", 0);
		lines = (int)c8l_field_num(L, 3, "lines", max > 0 ? 1 : 0);
	}
	const char *family = lua_istable(L, 3) ?
		c8l_field_str(L, 3, "family", NULL) : NULL;
	c8ui_text_size(family ? family : d->w ? c8ui_widget_font(d->w) : NULL,
		font_of(L, 3), text, max, lines, &width, &height);
	lua_pushnumber(L, width);
	lua_pushnumber(L, height);
	return 2;
}

/* Icons by name, loaded once and kept for the app's life */
struct c8ui_icon *c8l_icon(const char *name) {
	static GHashTable *icons;
	if (icons == NULL) {
		icons = g_hash_table_new(g_str_hash, g_str_equal);
	}
	gpointer icon;
	if (!g_hash_table_lookup_extended(icons, name, NULL, &icon)) {
		icon = c8ui_icon_load(NULL, name);
		g_hash_table_insert(icons, g_strdup(name), icon);
	}
	return icon;
}

/* g:icon(name, x, y, size): fitted in the square */
static int g_icon(lua_State *L) {
	struct draw *d = draw_at(L);
	struct c8ui_icon *icon = c8l_icon(luaL_checkstring(L, 2));
	double size = luaL_checknumber(L, 5);
	if (icon) {
		c8ui_icon_draw_fit(d->cr, icon, luaL_checknumber(L, 3) + size / 2,
			luaL_checknumber(L, 4) + size / 2, size);
	}
	lua_pushboolean(L, icon != NULL);
	return 1;
}

cairo_surface_t *c8l_image(lua_State *L, int index) {
	struct picture *p = luaL_testudata(L, index, IMAGE_META);
	return p ? p->surface : NULL;
}

/* g:image(picture, x, y, width, height [, "cover" | "fit" | "stretch"]) */
static int g_image(lua_State *L) {
	struct draw *d = draw_at(L);
	cairo_surface_t *surface = c8l_image(L, 2);
	if (surface == NULL) {
		return 0;
	}
	double x = luaL_checknumber(L, 3), y = luaL_checknumber(L, 4);
	double w = luaL_checknumber(L, 5), h = luaL_checknumber(L, 6);
	const char *mode = luaL_optstring(L, 7, "cover");
	if (strcmp(mode, "fit") == 0) {
		c8ui_draw_surface_fit(d->cr, surface, x, y, w, h, 1);
	} else if (strcmp(mode, "stretch") == 0) {
		c8ui_draw_surface(d->cr, surface, x, y, w, h);
	} else {
		c8ui_draw_surface_cover(d->cr, surface, x, y, w, h);
	}
	return 0;
}

/* g.fg, g.bg, g.accent, g.dark: the colours where it draws */
static int g_index(lua_State *L) {
	struct draw *d = luaL_checkudata(L, 1, DRAW_META);
	const char *key = lua_tostring(L, 2);
	if (key && luaL_getmetafield(L, 1, "methods") == LUA_TTABLE) {
		if (lua_getfield(L, -1, key) != LUA_TNIL) {
			return 1;
		}
		lua_pop(L, 2);
	}
	if (key == NULL || d->cr == NULL) {
		return 0;
	}
	struct c8ui_colors c = colors_of(d);
	if (strcmp(key, "fg") == 0) {
		lua_pushinteger(L, c.fg);
	} else if (strcmp(key, "bg") == 0) {
		lua_pushinteger(L, c.bg);
	} else if (strcmp(key, "accent") == 0) {
		lua_pushinteger(L, c.accent);
	} else if (strcmp(key, "secondary") == 0) {
		lua_pushnumber(L, c.fg_secondary);
	} else if (strcmp(key, "dark") == 0) {
		lua_pushboolean(L, c.dark);
	} else {
		return 0;
	}
	return 1;
}

static const luaL_Reg draw_methods[] = {
	{ "rect", g_rect },
	{ "frame", g_frame },
	{ "line", g_line },
	{ "circle", g_circle },
	{ "text", g_text },
	{ "measure", g_measure },
	{ "icon", g_icon },
	{ "image", g_image },
	{ "shape", g_shape },
	{ "paint", g_paint },
	{ NULL, NULL },
};

/* Pictures */

static int picture_gc(lua_State *L) {
	struct picture *p = luaL_checkudata(L, 1, IMAGE_META);
	if (p->surface) {
		cairo_surface_destroy(p->surface);
		p->surface = NULL;
	}
	return 0;
}

static int picture_size(lua_State *L) {
	struct picture *p = luaL_checkudata(L, 1, IMAGE_META);
	lua_pushinteger(L, cairo_image_surface_get_width(p->surface));
	lua_pushinteger(L, cairo_image_surface_get_height(p->surface));
	return 2;
}

/* c8.picture(path [, max]): a picture file, shrunk to fit a max px
 * square when given; nil and why when it can't be read. Decoded here
 * and now, so keep big ones off the first frame. */
static int l_picture(lua_State *L) {
	const char *path = luaL_checkstring(L, 1);
	int max = (int)luaL_optinteger(L, 2, 0);
	GError *error = NULL;
	GdkPixbuf *raw = max > 0 ?
		gdk_pixbuf_new_from_file_at_scale(path, max, max, TRUE, &error) :
		gdk_pixbuf_new_from_file(path, &error);
	if (raw == NULL) {
		lua_pushnil(L);
		lua_pushstring(L, error ? error->message : "not a picture");
		g_clear_error(&error);
		return 2;
	}
	GdkPixbuf *pixbuf = gdk_pixbuf_apply_embedded_orientation(raw);
	g_object_unref(raw);
	struct picture *p = lua_newuserdatauv(L, sizeof(*p), 0);
	p->surface = c8ui_surface_from_pixels(gdk_pixbuf_get_pixels(pixbuf),
		gdk_pixbuf_get_width(pixbuf), gdk_pixbuf_get_height(pixbuf),
		gdk_pixbuf_get_rowstride(pixbuf), gdk_pixbuf_get_n_channels(pixbuf));
	g_object_unref(pixbuf);
	luaL_setmetatable(L, IMAGE_META);
	return 1;
}

/* c8.draw_picture(width, height, function(g) end): a picture drawn with
 * g, transparent where nothing is drawn; for c8.image, g:image and a
 * hub's background */
static int l_draw_picture(lua_State *L) {
	int width = (int)luaL_checkinteger(L, 1);
	int height = (int)luaL_checkinteger(L, 2);
	luaL_checktype(L, 3, LUA_TFUNCTION);
	luaL_argcheck(L, width > 0 && height > 0 && width <= 8192 &&
		height <= 8192, 1, "a size from 1 to 8192");
	struct picture *p = lua_newuserdatauv(L, sizeof(*p), 0);
	p->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width,
		height);
	luaL_setmetatable(L, IMAGE_META);
	int pic = lua_gettop(L);
	cairo_t *cr = cairo_create(p->surface);
	lua_pushvalue(L, 3);
	c8l_draw_begin(L, cr, NULL);
	int g = lua_gettop(L);
	lua_pushvalue(L, g);
	lua_insert(L, g - 1); // g, fn, g
	c8l_call(L, 1, 0);
	c8l_draw_end(L, g - 1);
	cairo_destroy(cr);
	cairo_surface_flush(p->surface);
	lua_settop(L, pic);
	return 1;
}

/* c8.gradient(x1, y1, x2, y2, { { 0, color [, alpha] }, { 1, color } }):
 * a colour going from one to another along the line, to give g where a
 * colour goes */
static int l_gradient(lua_State *L) {
	luaL_checktype(L, 5, LUA_TTABLE);
	struct gradient *grad = lua_newuserdatauv(L, sizeof(*grad), 0);
	grad->pattern = cairo_pattern_create_linear(luaL_checknumber(L, 1),
		luaL_checknumber(L, 2), luaL_checknumber(L, 3), luaL_checknumber(L, 4));
	luaL_setmetatable(L, GRADIENT_META);
	lua_Integer n = luaL_len(L, 5);
	for (lua_Integer i = 1; i <= n; i++) {
		if (lua_geti(L, 5, i) == LUA_TTABLE) {
			lua_geti(L, -1, 1);
			lua_geti(L, -2, 2);
			lua_geti(L, -3, 3);
			uint32_t rgb = c8l_color(L, -2, 0);
			cairo_pattern_add_color_stop_rgba(grad->pattern, lua_tonumber(L, -3),
				((rgb >> 16) & 0xff) / 255.0, ((rgb >> 8) & 0xff) / 255.0,
				(rgb & 0xff) / 255.0, luaL_optnumber(L, -1, 1));
			lua_pop(L, 3);
		}
		lua_pop(L, 1);
	}
	return 1;
}

static int gradient_gc(lua_State *L) {
	struct gradient *grad = luaL_checkudata(L, 1, GRADIENT_META);
	if (grad->pattern) {
		cairo_pattern_destroy(grad->pattern);
		grad->pattern = NULL;
	}
	return 0;
}

/* Events: { type, x, y, button, dx, dy, key, text, ctrl, shift, alt,
 * super } with what the type has */
void c8l_push_event(lua_State *L, const struct c8ui_event *ev) {
	static const char *const types[] = {
		[C8UI_EVENT_PRESS] = "press", [C8UI_EVENT_RELEASE] = "release",
		[C8UI_EVENT_MOTION] = "motion", [C8UI_EVENT_ENTER] = "enter",
		[C8UI_EVENT_LEAVE] = "leave", [C8UI_EVENT_SCROLL] = "scroll",
		[C8UI_EVENT_KEY] = "key", [C8UI_EVENT_FOCUS_IN] = "focus_in",
		[C8UI_EVENT_FOCUS_OUT] = "focus_out",
		[C8UI_EVENT_SCROLL_STOP] = "scroll_stop",
		[C8UI_EVENT_TOUCH_DOWN] = "touch_down",
		[C8UI_EVENT_TOUCH_MOTION] = "touch_motion",
		[C8UI_EVENT_TOUCH_UP] = "touch_up",
		[C8UI_EVENT_TOUCH_CANCEL] = "touch_cancel",
		[C8UI_EVENT_SWIPE_BEGIN] = "swipe_begin",
		[C8UI_EVENT_SWIPE_UPDATE] = "swipe_update",
		[C8UI_EVENT_SWIPE_END] = "swipe_end",
		[C8UI_EVENT_PINCH_BEGIN] = "pinch_begin",
		[C8UI_EVENT_PINCH_UPDATE] = "pinch_update",
		[C8UI_EVENT_PINCH_END] = "pinch_end",
	};
	lua_createtable(L, 0, 12);
	lua_pushstring(L, (size_t)ev->type < G_N_ELEMENTS(types) &&
		types[ev->type] ? types[ev->type] : "other");
	lua_setfield(L, -2, "type");
	lua_pushnumber(L, ev->x);
	lua_setfield(L, -2, "x");
	lua_pushnumber(L, ev->y);
	lua_setfield(L, -2, "y");
	lua_pushnumber(L, ev->dx);
	lua_setfield(L, -2, "dx");
	lua_pushnumber(L, ev->dy);
	lua_setfield(L, -2, "dy");
	if (ev->type == C8UI_EVENT_PRESS || ev->type == C8UI_EVENT_RELEASE) {
		lua_pushstring(L, ev->button == C8UI_BUTTON_LEFT ? "left" :
			ev->button == C8UI_BUTTON_RIGHT ? "right" :
			ev->button == C8UI_BUTTON_BACK ? "back" : "other");
		lua_setfield(L, -2, "button");
	}
	if (ev->type == C8UI_EVENT_KEY) {
		/* The key's name as xkb has it: "Escape", "Return", "a", "F5" */
		char name[64] = "";
		xkb_keysym_get_name(ev->base_sym ? ev->base_sym : ev->sym, name,
			sizeof(name));
		lua_pushstring(L, name);
		lua_setfield(L, -2, "key");
		if (ev->text) {
			lua_pushstring(L, ev->text);
			lua_setfield(L, -2, "text");
		}
	}
	if (ev->type == C8UI_EVENT_PINCH_UPDATE) {
		lua_pushnumber(L, ev->scale);
		lua_setfield(L, -2, "scale");
	}
	lua_pushboolean(L, ev->mods & C8UI_MOD_CTRL);
	lua_setfield(L, -2, "ctrl");
	lua_pushboolean(L, ev->mods & C8UI_MOD_SHIFT);
	lua_setfield(L, -2, "shift");
	lua_pushboolean(L, ev->mods & C8UI_MOD_ALT);
	lua_setfield(L, -2, "alt");
	lua_pushboolean(L, ev->mods & C8UI_MOD_SUPER);
	lua_setfield(L, -2, "super");
}

void c8l_draw_open(lua_State *L) {
	lua_pushcfunction(L, l_picture);
	lua_setfield(L, -2, "picture");
	lua_pushcfunction(L, l_draw_picture);
	lua_setfield(L, -2, "draw_picture");
	lua_pushcfunction(L, l_gradient);
	lua_setfield(L, -2, "gradient");

	luaL_newmetatable(L, GRADIENT_META);
	lua_pushcfunction(L, gradient_gc);
	lua_setfield(L, -2, "__gc");
	lua_pop(L, 1);

	luaL_newmetatable(L, DRAW_META);
	lua_pushcfunction(L, g_index);
	lua_setfield(L, -2, "__index");
	luaL_newlib(L, draw_methods);
	lua_setfield(L, -2, "methods");
	lua_pop(L, 1);

	luaL_newmetatable(L, IMAGE_META);
	lua_pushcfunction(L, picture_gc);
	lua_setfield(L, -2, "__gc");
	lua_newtable(L);
	lua_pushcfunction(L, picture_size);
	lua_setfield(L, -2, "size");
	lua_setfield(L, -2, "__index");
	lua_pop(L, 1);
}
