/*
 * Pictures for the lists and the preview: SteamGridDB's thumbnails
 * (downloaded into the cache once) and local files, decoded on a thread
 * and kept by reference and size.
 */
#include <stdio.h>
#include <string.h>
#include <gio/gio.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include "tiles.h"

enum state { LOADING, READY, FAILED };

struct entry {
	enum state state;
	cairo_surface_t *surface;
	char *path; // the file to decode
	int max;
};

static GHashTable *cache; // "max|ref" -> struct entry
static tm_picture_fn ready_fn;
static void *ready_data;

void tm_pictures_on_ready(tm_picture_fn fn, void *data) {
	ready_fn = fn;
	ready_data = data;
}

static void entry_free(gpointer p) {
	struct entry *e = p;
	if (e->surface) {
		cairo_surface_destroy(e->surface);
	}
	g_free(e->path);
	g_free(e);
}

static cairo_surface_t *from_pixbuf(GdkPixbuf *pb) {
	if (pb == NULL) {
		return NULL;
	}
	GdkPixbuf *rgba = gdk_pixbuf_get_has_alpha(pb) ? g_object_ref(pb) :
		gdk_pixbuf_add_alpha(pb, FALSE, 0, 0, 0);
	g_object_unref(pb);
	int w = gdk_pixbuf_get_width(rgba), h = gdk_pixbuf_get_height(rgba);
	int stride = gdk_pixbuf_get_rowstride(rgba);
	const guint8 *src = gdk_pixbuf_read_pixels(rgba);
	cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h);
	unsigned char *dst = cairo_image_surface_get_data(s);
	int dstride = cairo_image_surface_get_stride(s);
	for (int y = 0; y < h; y++) {
		const guint8 *p = src + y * stride;
		guint32 *q = (guint32 *)(dst + y * dstride);
		for (int x = 0; x < w; x++, p += 4) {
			guint32 a = p[3];
			q[x] = a << 24 | (p[0] * a / 255) << 16 | (p[1] * a / 255) << 8 |
				p[2] * a / 255;
		}
	}
	cairo_surface_mark_dirty(s);
	g_object_unref(rgba);
	return s;
}

/* Loads a file now, for the preview; NULL if it won't */
static cairo_surface_t *tm_picture_file(const char *path, int max) {
	return from_pixbuf(gdk_pixbuf_new_from_file_at_scale(path, max, max, TRUE,
		NULL));
}

/* Decoding, on a thread */

static void decode(GTask *task, gpointer src, gpointer data,
		GCancellable *c) {
	struct entry *e = data;
	g_task_return_pointer(task, tm_picture_file(e->path, e->max), NULL);
}

static void decoded(GObject *src, GAsyncResult *res, gpointer data) {
	char *key = data;
	cairo_surface_t *s = g_task_propagate_pointer(G_TASK(res), NULL);
	struct entry *e = g_hash_table_lookup(cache, key);
	if (e) {
		e->surface = s;
		e->state = s ? READY : FAILED;
		if (ready_fn) {
			ready_fn(ready_data);
		}
	} else if (s) {
		cairo_surface_destroy(s); // forgotten meanwhile
	}
	g_free(key);
}

static void start_decode(const char *key, struct entry *e) {
	/* The task's data is the entry, which stays in the table until
	 * forgotten; forgetting during a decode is what the key check in
	 * decoded() is for, so give it a copy of what it reads */
	struct entry *copy = g_new0(struct entry, 1);
	copy->path = g_strdup(e->path);
	copy->max = e->max;
	GTask *task = g_task_new(NULL, NULL, decoded, g_strdup(key));
	g_task_set_task_data(task, copy, entry_free);
	g_task_run_in_thread(task, decode);
	g_object_unref(task);
}

static void downloaded(int status, const char *body, void *data) {
	char *key = data;
	struct entry *e = g_hash_table_lookup(cache, key);
	if (e && status == 200) {
		start_decode(key, e);
	} else if (e) {
		e->state = FAILED;
	}
	g_free(key);
}

static char *cache_file(const char *url) {
	char *sum = g_compute_checksum_for_string(G_CHECKSUM_SHA1, url, -1);
	char *path = g_build_filename(g_get_user_cache_dir(), "cont8nuum",
		"tilemaker", sum, NULL);
	g_free(sum);
	return path;
}

cairo_surface_t *tm_picture(const char *ref, int max) {
	if (ref == NULL || ref[0] == '\0') {
		return NULL;
	}
	if (cache == NULL) {
		cache = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
			entry_free);
	}
	char *key = g_strdup_printf("%d|%s", max, ref);
	struct entry *e = g_hash_table_lookup(cache, key);
	if (e) {
		g_free(key);
		return e->surface;
	}
	e = g_new0(struct entry, 1);
	e->max = max;
	g_hash_table_insert(cache, g_strdup(key), e);
	if (g_str_has_prefix(ref, "https://")) {
		e->path = cache_file(ref);
		if (g_file_test(e->path, G_FILE_TEST_IS_REGULAR)) {
			start_decode(key, e);
		} else {
			tm_download(ref, e->path, downloaded, g_strdup(key));
		}
	} else if (ref[0] == '/') {
		e->path = g_strdup(ref);
		start_decode(key, e);
	} else {
		e->state = FAILED;
	}
	g_free(key);
	return NULL;
}
