#include <glib.h>
#include <math.h>
#include <stdlib.h>
#include "c8ui-private.h"

/* Drawing something once and copying it after. A window is drawn again
 * whole for every frame of a scroll or an animation, in software, so what
 * costs milliseconds each time (shrinking a photo, gradients over it,
 * laying out words) drops frames once there are a dozen on screen. Two
 * things here: pictures drawn at another size keep a copy at that size,
 * and anything at all can be kept as the pixels it came out as. */

/* How the cairo context maps to the screen's pixels: a plain scale, or
 * not (turned, mirrored), when nothing is kept */
static bool pixel_scale(cairo_t *cr, double *sx, double *sy) {
	double ax = 1, ay = 0, bx = 0, by = 1;
	cairo_user_to_device_distance(cr, &ax, &ay);
	cairo_user_to_device_distance(cr, &bx, &by);
	*sx = ax;
	*sy = by;
	return ay == 0 && bx == 0 && ax > 0 && by > 0;
}

/* pw x ph pixels of surface starting on the whole pixel nearest x, y, a
 * pixel each: a plain copy, which is the fast way */
static void copy_pixels(cairo_t *cr, cairo_surface_t *surface, double x,
		double y, int pw, int ph, double sx, double sy) {
	double px = x, py = y;
	cairo_user_to_device(cr, &px, &py);
	px = floor(px + 0.5);
	py = floor(py + 0.5);
	cairo_device_to_user(cr, &px, &py);
	cairo_save(cr);
	cairo_translate(cr, px, py);
	cairo_scale(cr, 1 / sx, 1 / sy);
	cairo_set_source_surface(cr, surface, 0, 0);
	cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_NEAREST);
	cairo_rectangle(cr, 0, 0, pw, ph);
	cairo_fill(cr);
	cairo_restore(cr);
}

/* Pictures: a copy at the size drawn, kept with the picture (and freed
 * with it). Two sizes each, for one shown in a list and on a page. */

#define SIZES 2

struct sizes {
	cairo_surface_t *scaled[SIZES];
	int next;
};

static cairo_user_data_key_t sizes_key;

static void sizes_free(void *data) {
	struct sizes *s = data;
	for (int i = 0; i < SIZES; i++) {
		if (s->scaled[i]) {
			cairo_surface_destroy(s->scaled[i]);
		}
	}
	free(s);
}

static cairo_surface_t *scaled_copy(cairo_surface_t *surface, int pw, int ph) {
	struct sizes *s = cairo_surface_get_user_data(surface, &sizes_key);
	if (s == NULL) {
		s = calloc(1, sizeof(*s));
		if (cairo_surface_set_user_data(surface, &sizes_key, s, sizes_free) !=
				CAIRO_STATUS_SUCCESS) {
			free(s);
			return NULL;
		}
	}
	for (int i = 0; i < SIZES; i++) {
		if (s->scaled[i] && cairo_image_surface_get_width(s->scaled[i]) == pw &&
				cairo_image_surface_get_height(s->scaled[i]) == ph) {
			return s->scaled[i];
		}
	}
	cairo_surface_t *out = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, pw,
		ph);
	if (cairo_surface_status(out) != CAIRO_STATUS_SUCCESS) {
		cairo_surface_destroy(out);
		return NULL;
	}
	cairo_t *cr = cairo_create(out);
	cairo_scale(cr, (double)pw / cairo_image_surface_get_width(surface),
		(double)ph / cairo_image_surface_get_height(surface));
	cairo_set_source_surface(cr, surface, 0, 0);
	cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_GOOD);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_paint(cr);
	cairo_destroy(cr);
	int slot = s->next;
	s->next = (s->next + 1) % SIZES;
	if (s->scaled[slot]) {
		cairo_surface_destroy(s->scaled[slot]);
	}
	s->scaled[slot] = out;
	return out;
}

void c8ui_draw_surface(cairo_t *cr, cairo_surface_t *surface, double x,
		double y, double width, double height) {
	if (surface == NULL || width <= 0 || height <= 0 ||
			cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS) {
		return;
	}
	bool image = cairo_surface_get_type(surface) == CAIRO_SURFACE_TYPE_IMAGE;
	double iw = image ? cairo_image_surface_get_width(surface) : 0;
	double ih = image ? cairo_image_surface_get_height(surface) : 0;
	double sx, sy;
	if (image && iw > 0 && ih > 0 && pixel_scale(cr, &sx, &sy)) {
		int pw = (int)floor(width * sx + 0.5), ph = (int)floor(height * sy + 0.5);
		/* Only smaller: bigger is cheap as it is, and a copy would be
		 * bigger than the picture */
		if (pw == iw && ph == ih) {
			copy_pixels(cr, surface, x, y, pw, ph, sx, sy);
			return;
		}
		if (pw > 0 && ph > 0 && pw <= iw && ph <= ih) {
			cairo_surface_t *copy = scaled_copy(surface, pw, ph);
			if (copy) {
				copy_pixels(cr, copy, x, y, pw, ph, sx, sy);
				return;
			}
		}
	}
	if (iw <= 0 || ih <= 0) {
		return;
	}
	cairo_save(cr);
	cairo_translate(cr, x, y);
	cairo_scale(cr, width / iw, height / ih);
	cairo_set_source_surface(cr, surface, 0, 0);
	cairo_pattern_set_filter(cairo_get_source(cr),
		width < iw * 0.5 ? CAIRO_FILTER_GOOD : CAIRO_FILTER_BILINEAR);
	cairo_paint(cr);
	cairo_restore(cr);
}

void c8ui_draw_surface_cover(cairo_t *cr, cairo_surface_t *surface, double x,
		double y, double width, double height) {
	if (surface == NULL ||
			cairo_surface_get_type(surface) != CAIRO_SURFACE_TYPE_IMAGE) {
		return;
	}
	double iw = cairo_image_surface_get_width(surface);
	double ih = cairo_image_surface_get_height(surface);
	if (iw <= 0 || ih <= 0 || width <= 0 || height <= 0) {
		return;
	}
	double scale = fmax(width / iw, height / ih);
	cairo_save(cr);
	cairo_rectangle(cr, x, y, width, height);
	cairo_clip(cr);
	c8ui_draw_surface(cr, surface, x + (width - iw * scale) / 2,
		y + (height - ih * scale) / 2, iw * scale, ih * scale);
	cairo_restore(cr);
}

void c8ui_draw_surface_fit(cairo_t *cr, cairo_surface_t *surface, double x,
		double y, double width, double height, double max_scale) {
	if (surface == NULL ||
			cairo_surface_get_type(surface) != CAIRO_SURFACE_TYPE_IMAGE) {
		return;
	}
	double iw = cairo_image_surface_get_width(surface);
	double ih = cairo_image_surface_get_height(surface);
	if (iw <= 0 || ih <= 0 || width <= 0 || height <= 0) {
		return;
	}
	double scale = fmin(width / iw, height / ih);
	if (max_scale > 0 && scale > max_scale) {
		scale = max_scale;
	}
	c8ui_draw_surface(cr, surface, x + (width - iw * scale) / 2,
		y + (height - ih * scale) / 2, iw * scale, ih * scale);
}

/* Drawings: the pixels they came out as. Every one is in one queue, the
 * least recently drawn first, and those go when all of them together
 * pass KEPT_BYTES (a resize draws everything again, bigger). */

#define KEPT_BYTES (64u << 20)
#define KEPT_SIDE 8192

struct c8ui_kept {
	struct c8ui_kept **slot; // where its owner holds it: cleared when it goes
	cairo_surface_t *surface;
	uint32_t state;
	int pw, ph;
	size_t bytes;
	GList link; // in kept_queue
};

static GQueue kept_queue;
static size_t kept_bytes;

void c8ui_kept_drop(struct c8ui_kept **slot) {
	struct c8ui_kept *k = slot ? *slot : NULL;
	if (k == NULL) {
		return;
	}
	*k->slot = NULL;
	g_queue_unlink(&kept_queue, &k->link);
	kept_bytes -= k->bytes;
	cairo_surface_destroy(k->surface);
	free(k);
}

void c8ui_kept_draw(struct c8ui_kept **slot, cairo_t *cr, struct c8ui_rect r,
		uint32_t state, c8ui_kept_fn fn, void *data) {
	double sx, sy;
	int pw = 0, ph = 0;
	bool plain = pixel_scale(cr, &sx, &sy);
	if (plain) {
		pw = (int)ceil(r.width * sx);
		ph = (int)ceil(r.height * sy);
	}
	if (!plain || pw <= 0 || ph <= 0 || pw > KEPT_SIDE || ph > KEPT_SIDE) {
		/* Turned, nothing or huge: as it comes */
		c8ui_kept_drop(slot);
		cairo_save(cr);
		cairo_translate(cr, r.x, r.y);
		fn(cr, (struct c8ui_rect){ 0, 0, r.width, r.height }, data);
		cairo_restore(cr);
		return;
	}
	struct c8ui_kept *k = *slot;
	if (k && k->state == state && k->pw == pw && k->ph == ph) {
		g_queue_unlink(&kept_queue, &k->link);
		g_queue_push_tail_link(&kept_queue, &k->link);
		copy_pixels(cr, k->surface, r.x, r.y, pw, ph, sx, sy);
		return;
	}
	c8ui_kept_drop(slot);
	cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		pw, ph);
	if (cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS) {
		cairo_surface_destroy(surface);
		cairo_save(cr);
		cairo_translate(cr, r.x, r.y);
		fn(cr, (struct c8ui_rect){ 0, 0, r.width, r.height }, data);
		cairo_restore(cr);
		return;
	}
	cairo_t *own = cairo_create(surface);
	cairo_scale(own, sx, sy);
	bool final = fn(own, (struct c8ui_rect){ 0, 0, r.width, r.height }, data);
	cairo_destroy(own);
	copy_pixels(cr, surface, r.x, r.y, pw, ph, sx, sy);
	if (!final) {
		/* Something in it is still coming: this once */
		cairo_surface_destroy(surface);
		return;
	}
	k = calloc(1, sizeof(*k));
	k->slot = slot;
	k->surface = surface;
	k->state = state;
	k->pw = pw;
	k->ph = ph;
	k->bytes = (size_t)cairo_image_surface_get_stride(surface) * ph;
	k->link.data = k;
	g_queue_push_tail_link(&kept_queue, &k->link);
	kept_bytes += k->bytes;
	*slot = k;
	/* Never the one just made */
	while (kept_bytes > KEPT_BYTES && kept_queue.length > 1) {
		struct c8ui_kept *old = g_queue_peek_head(&kept_queue);
		c8ui_kept_drop(old->slot);
	}
}

cairo_surface_t *c8ui_surface_from_pixels(const unsigned char *pixels,
		int width, int height, int stride, int channels) {
	cairo_surface_t *img = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		width, height);
	unsigned char *dst = cairo_image_surface_get_data(img);
	int dstride = cairo_image_surface_get_stride(img);
	for (int y = 0; y < height; y++) {
		const unsigned char *s = pixels + (size_t)y * stride;
		uint32_t *d = (uint32_t *)(dst + y * dstride);
		for (int x = 0; x < width; x++, s += channels) {
			uint32_t a = channels == 4 ? s[3] : 255;
			d[x] = a << 24 | (s[0] * a / 255) << 16 |
				(s[1] * a / 255) << 8 | (s[2] * a / 255);
		}
	}
	cairo_surface_mark_dirty(img);
	return img;
}
