/*
 * Pictures of stories: downloaded into the cache (a file per address) and
 * decoded when something draws them, on a thread: a big one takes tens of
 * milliseconds, and a hub being panned asks for one after another.
 */
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <string.h>
#include "news.h"

#define MAX_PX 480
#define LOADED_MAX 64 // decoded pictures kept
#define LARGE_PX 1920 // for a picture across the window: the top story's
#define LARGE_MAX 2
#define DOWNLOADS_MAX 4

struct entry {
	char *url, *path;
	cairo_surface_t *surface, *large;
	bool downloading, decoding, failed, on_disk;
	bool decoding_large, large_failed;
	GList *lru; // in the queue of decoded ones
	GList *large_lru;
};

static GHashTable *entries; // url -> struct entry
static GQueue lru; // entries with a surface, least recently used first
static GQueue large_lru; // the same for the large ones
static GQueue waiting; // entries to download
static int downloading;
static image_fn ready_fn;
static void *ready_data;

bool news_image_missed;

void news_image_on_ready(image_fn fn, void *data) {
	ready_fn = fn;
	ready_data = data;
}

static struct entry *entry_for(const char *url) {
	if (entries == NULL) {
		entries = g_hash_table_new(g_str_hash, g_str_equal);
	}
	struct entry *e = g_hash_table_lookup(entries, url);
	if (e) {
		return e;
	}
	e = g_new0(struct entry, 1);
	e->url = g_strdup(url);
	char *hash = g_compute_checksum_for_string(G_CHECKSUM_SHA1, url, -1);
	char *name = g_strconcat("img/", hash, NULL);
	e->path = news_cache_path(name);
	e->on_disk = g_file_test(e->path, G_FILE_TEST_IS_REGULAR);
	g_free(hash);
	g_free(name);
	g_hash_table_insert(entries, e->url, e);
	return e;
}

/* No bigger than px either way; smaller ones stay as they are (a favicon
 * blown up to 480 px would only cost memory) */
static cairo_surface_t *decode(const char *path, int px) {
	int fw = 0, fh = 0;
	gdk_pixbuf_get_file_info(path, &fw, &fh);
	GdkPixbuf *pb = fw > 0 && fw <= px && fh <= px ?
		gdk_pixbuf_new_from_file(path, NULL) :
		gdk_pixbuf_new_from_file_at_scale(path, px, px, TRUE, NULL);
	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);
	cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h);
	unsigned char *dst = cairo_image_surface_get_data(s);
	int dst_stride = cairo_image_surface_get_stride(s);
	const unsigned char *src = gdk_pixbuf_read_pixels(rgba);
	int stride = gdk_pixbuf_get_rowstride(rgba);
	for (int y = 0; y < h; y++) {
		uint32_t *row = (uint32_t *)(dst + y * dst_stride);
		const unsigned char *p = src + y * stride;
		for (int x = 0; x < w; x++, p += 4) {
			unsigned a = p[3];
			row[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;
}

static void pump(void);

static void downloaded(int status, const char *etag, const char *modified,
		void *data) {
	struct entry *e = data;
	e->downloading = false;
	downloading--;
	if (status == 200) {
		e->on_disk = true;
		/* Is it a picture? */
		if (gdk_pixbuf_get_file_info(e->path, NULL, NULL) == NULL) {
			e->on_disk = false;
			e->failed = true;
			g_unlink(e->path);
		}
	} else {
		e->failed = true;
	}
	if (e->on_disk && ready_fn) {
		ready_fn(e->url, ready_data);
	}
	pump();
}

static void pump(void) {
	while (downloading < DOWNLOADS_MAX && !g_queue_is_empty(&waiting)) {
		struct entry *e = g_queue_pop_head(&waiting);
		e->downloading = true;
		downloading++;
		fetch_start(e->url, e->path, NULL, NULL, downloaded, e);
	}
}

const char *news_image_path(const char *url) {
	if (url == NULL || url[0] == '\0') {
		return NULL;
	}
	struct entry *e = entry_for(url);
	return e->on_disk && !e->failed ? e->path : NULL;
}

/* Decoding, off the main loop. Entries are never freed, so the task can
 * hold one. */
static void decode_thread(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	g_task_return_pointer(task, decode(data, MAX_PX), NULL);
}

static void decoded(GObject *source, GAsyncResult *res, gpointer data) {
	struct entry *e = data;
	e->decoding = false;
	e->surface = g_task_propagate_pointer(G_TASK(res), NULL);
	if (e->surface == NULL) {
		e->failed = true;
		e->on_disk = false;
		g_unlink(e->path);
		return;
	}
	e->lru = g_list_alloc();
	e->lru->data = e;
	g_queue_push_tail_link(&lru, e->lru);
	while (g_queue_get_length(&lru) > LOADED_MAX) {
		GList *old = g_queue_pop_head_link(&lru);
		struct entry *o = old->data;
		cairo_surface_destroy(o->surface);
		o->surface = NULL;
		o->lru = NULL;
		g_list_free(old);
	}
	if (ready_fn) {
		ready_fn(e->url, ready_data);
	}
}

cairo_surface_t *news_image(const char *url) {
	if (url == NULL || url[0] == '\0') {
		return NULL;
	}
	struct entry *e = entry_for(url);
	if (e->surface) {
		g_queue_unlink(&lru, e->lru);
		g_queue_push_tail_link(&lru, e->lru);
		return e->surface;
	}
	if (e->failed) {
		return NULL;
	}
	if (e->on_disk) {
		if (!e->decoding) {
			e->decoding = true;
			GTask *task = g_task_new(NULL, NULL, decoded, e);
			g_task_set_task_data(task, g_strdup(e->path), g_free);
			g_task_run_in_thread(task, decode_thread);
			g_object_unref(task);
		}
		news_image_missed = true;
		return NULL;
	}
	if (!e->downloading && !g_queue_find(&waiting, e) &&
			(g_str_has_prefix(url, "http://") || g_str_has_prefix(url, "https://") ||
			(g_getenv("C8_NEWS_ALLOW_FILE") && g_str_has_prefix(url, "file://")))) {
		g_queue_push_tail(&waiting, e);
		pump();
	}
	if (e->downloading || g_queue_find(&waiting, e)) {
		news_image_missed = true;
	}
	return NULL;
}

struct large_job {
	struct entry *e;
	char *path;
};

static void large_thread(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	struct large_job *job = data;
	g_task_return_pointer(task, decode(job->path, LARGE_PX), NULL);
}

static void large_job_free(gpointer data) {
	struct large_job *job = data;
	g_free(job->path);
	g_free(job);
}

static void large_decoded(GObject *source, GAsyncResult *res, gpointer data) {
	struct entry *e = data;
	e->decoding_large = false;
	e->large = g_task_propagate_pointer(G_TASK(res), NULL);
	if (e->large == NULL) {
		e->large_failed = true; // the small one will have to do
		return;
	}
	e->large_lru = g_list_alloc();
	e->large_lru->data = e;
	g_queue_push_tail_link(&large_lru, e->large_lru);
	while (g_queue_get_length(&large_lru) > LARGE_MAX) {
		GList *old = g_queue_pop_head_link(&large_lru);
		struct entry *o = old->data;
		cairo_surface_destroy(o->large);
		o->large = NULL;
		o->large_lru = NULL;
		g_list_free(old);
	}
	if (ready_fn) {
		ready_fn(e->url, ready_data);
	}
}

/* The small one until the large one is decoded (on a thread too: it is
 * the slowest of all), which news_image_on_ready's fn then hears of */
cairo_surface_t *news_image_large(const char *url) {
	cairo_surface_t *small = news_image(url);
	if (small == NULL) {
		return NULL;
	}
	struct entry *e = entry_for(url);
	if (e->large) {
		g_queue_unlink(&large_lru, e->large_lru);
		g_queue_push_tail_link(&large_lru, e->large_lru);
		return e->large;
	}
	/* No more to it than the small one has: that's it */
	if (e->large_failed || (cairo_image_surface_get_width(small) < MAX_PX &&
			cairo_image_surface_get_height(small) < MAX_PX)) {
		return small;
	}
	if (!e->decoding_large) {
		e->decoding_large = true;
		struct large_job *job = g_new0(struct large_job, 1);
		job->e = e;
		job->path = g_strdup(e->path);
		GTask *task = g_task_new(NULL, NULL, large_decoded, e);
		g_task_set_task_data(task, job, large_job_free);
		g_task_run_in_thread(task, large_thread);
		g_object_unref(task);
	}
	news_image_missed = true; // what's drawn now isn't the last word
	return small;
}
