#include <ctype.h>
#include <dirent.h>
#include <pthread.h>
#include <sys/eventfd.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <glib.h>
#if C8UI_HAVE_SVG
#include <librsvg/rsvg.h>
#endif
#include "c8ui-private.h"

/*
 * Icon lookup following the freedesktop icon theme spec closely enough for
 * tiles: we want the biggest or scalable rendition of one icon, so
 * directories are tried scalable-first, then largest first.
 */

struct c8ui_icon {
	cairo_surface_t *png;
#if C8UI_HAVE_SVG
	RsvgHandle *svg;
	/* The SVG rasterised at the sizes last drawn (the latest first),
	 * since rendering it is slow and the same sizes are asked for again */
	struct raster {
		cairo_surface_t *surface;
		int w, h;
	} rasters[2];
#endif
	double width, height;
};

struct theme_dir {
	char *path;
	int size;
	bool scalable;
};

struct theme {
	struct theme *next;
	char *name;
	char **inherits;
	int inherits_len;
	struct theme_dir *dirs;
	int dirs_len;
	/* Icon name -> path of its best rendition, built on first lookup so a
	 * lookup is one hash probe rather than a stat per directory */
	GHashTable *index;
};

static struct theme *themes; /* cache of parsed index.theme files */
static bool themes_init;

#define MAX_ROOTS 16
static char *roots[MAX_ROOTS];
static int roots_len;

static void add_root(const char *fmt, const char *a) {
	if (roots_len == MAX_ROOTS || a == NULL || a[0] == '\0') {
		return;
	}
	char buf[1024];
	snprintf(buf, sizeof(buf), fmt, a);
	for (int i = 0; i < roots_len; i++) {
		if (strcmp(roots[i], buf) == 0) {
			return;
		}
	}
	roots[roots_len++] = strdup(buf);
}

static void init_roots(void) {
	const char *home = getenv("HOME");
	const char *data_home = getenv("XDG_DATA_HOME");
	if (data_home && data_home[0]) {
		add_root("%s/icons", data_home);
	} else {
		add_root("%s/.local/share/icons", home);
	}
	add_root("%s/.icons", home);
	const char *dirs = getenv("XDG_DATA_DIRS");
	if (dirs == NULL || dirs[0] == '\0') {
		dirs = "/usr/local/share:/usr/share";
	}
	char *copy = strdup(dirs);
	char *save = NULL;
	for (char *d = strtok_r(copy, ":", &save); d; d = strtok_r(NULL, ":", &save)) {
		add_root("%s/icons", d);
	}
	free(copy);
	/* Our own theme, even when the install prefix isn't in XDG_DATA_DIRS */
	add_root("%s/icons", C8UI_DATADIR);
}

static char *trim(char *s) {
	while (isspace((unsigned char)*s)) {
		s++;
	}
	char *end = s + strlen(s);
	while (end > s && isspace((unsigned char)end[-1])) {
		*--end = '\0';
	}
	return s;
}

static char **split_list(const char *value, int *len) {
	char **out = NULL;
	*len = 0;
	char *copy = strdup(value);
	char *save = NULL;
	for (char *t = strtok_r(copy, ",", &save); t; t = strtok_r(NULL, ",", &save)) {
		t = trim(t);
		if (t[0] == '\0') {
			continue;
		}
		out = realloc(out, sizeof(char *) * (*len + 1));
		out[(*len)++] = strdup(t);
	}
	free(copy);
	return out;
}

static int dir_cmp(const void *a, const void *b) {
	const struct theme_dir *da = a, *db = b;
	if (da->scalable != db->scalable) {
		return da->scalable ? -1 : 1;
	}
	return db->size - da->size;
}

static struct theme *theme_parse(const char *name) {
	FILE *f = NULL;
	char path[1100];
	for (int i = 0; i < roots_len && f == NULL; i++) {
		snprintf(path, sizeof(path), "%s/%s/index.theme", roots[i], name);
		f = fopen(path, "r");
	}
	if (f == NULL) {
		return NULL;
	}

	struct theme *theme = calloc(1, sizeof(*theme));
	theme->name = strdup(name);
	char section[512] = "";
	struct theme_dir *cur = NULL;
	char *line = NULL;
	size_t cap = 0;
	while (getline(&line, &cap, f) > 0) {
		char *s = trim(line);
		if (s[0] == '#' || s[0] == '\0') {
			continue;
		}
		if (s[0] == '[') {
			char *end = strchr(s, ']');
			if (end) {
				*end = '\0';
			}
			snprintf(section, sizeof(section), "%s", s + 1);
			cur = NULL;
			for (int i = 0; i < theme->dirs_len; i++) {
				if (strcmp(theme->dirs[i].path, section) == 0) {
					cur = &theme->dirs[i];
				}
			}
			continue;
		}
		char *eq = strchr(s, '=');
		if (eq == NULL) {
			continue;
		}
		*eq = '\0';
		char *key = trim(s), *value = trim(eq + 1);
		if (strcmp(section, "Icon Theme") == 0) {
			if (strcmp(key, "Inherits") == 0) {
				theme->inherits = split_list(value, &theme->inherits_len);
			} else if (strcmp(key, "Directories") == 0) {
				int n;
				char **dirs = split_list(value, &n);
				theme->dirs = calloc(n, sizeof(*theme->dirs));
				for (int i = 0; i < n; i++) {
					theme->dirs[i].path = dirs[i];
				}
				theme->dirs_len = n;
				free(dirs);
			}
		} else if (cur) {
			if (strcmp(key, "Size") == 0) {
				cur->size = atoi(value);
			} else if (strcmp(key, "Type") == 0) {
				cur->scalable = strcmp(value, "Scalable") == 0;
			}
		}
	}
	free(line);
	fclose(f);

	qsort(theme->dirs, theme->dirs_len, sizeof(*theme->dirs), dir_cmp);
	return theme;
}

static struct theme *theme_get(const char *name) {
	if (!themes_init) {
		init_roots();
		themes_init = true;
	}
	struct theme **tail = &themes;
	for (struct theme *t = themes; t; t = t->next) {
		if (strcmp(t->name, name) == 0) {
			return t;
		}
		tail = &t->next;
	}
	struct theme *theme = theme_parse(name);
	if (theme) {
		*tail = theme;
	}
	return theme;
}

static struct c8ui_icon *icon_from_file(const char *path) {
	if (access(path, R_OK) != 0) {
		return NULL;
	}
	size_t len = strlen(path);
	bool svg = len > 4 && (strcasecmp(path + len - 4, ".svg") == 0 ||
		(len > 5 && strcasecmp(path + len - 5, ".svgz") == 0));
	struct c8ui_icon *icon = calloc(1, sizeof(*icon));

	if (svg) {
#if C8UI_HAVE_SVG
		GError *err = NULL;
		icon->svg = rsvg_handle_new_from_file(path, &err);
		if (icon->svg == NULL) {
			fprintf(stderr, "c8ui: cannot load %s: %s\n", path,
				err ? err->message : "unknown error");
			g_clear_error(&err);
			free(icon);
			return NULL;
		}
		if (!rsvg_handle_get_intrinsic_size_in_pixels(icon->svg,
				&icon->width, &icon->height) ||
				icon->width <= 0 || icon->height <= 0) {
			icon->width = icon->height = 128;
		}
		return icon;
#else
		free(icon);
		return NULL;
#endif
	}

	icon->png = cairo_image_surface_create_from_png(path);
	if (cairo_surface_status(icon->png) != CAIRO_STATUS_SUCCESS) {
		cairo_surface_destroy(icon->png);
		free(icon);
		return NULL;
	}
	icon->width = cairo_image_surface_get_width(icon->png);
	icon->height = cairo_image_surface_get_height(icon->png);
	return icon;
}

static const char *extensions[] = {
#if C8UI_HAVE_SVG
	"svg",
#endif
	"png",
};

/* Adds the icons in one theme directory, keeping names already found in a
 * preferred directory */
static void index_dir(GHashTable *index, const char *dir) {
	DIR *d = opendir(dir);
	if (d == NULL) {
		return;
	}
	/* Within a directory, the extensions in order of preference */
	for (size_t e = 0; e < sizeof(extensions) / sizeof(extensions[0]); e++) {
		size_t elen = strlen(extensions[e]);
		struct dirent *ent;
		rewinddir(d);
		while ((ent = readdir(d)) != NULL) {
			size_t len = strlen(ent->d_name);
			if (len <= elen + 1 || ent->d_name[len - elen - 1] != '.' ||
					strcmp(ent->d_name + len - elen, extensions[e]) != 0) {
				continue;
			}
			char *key = g_strndup(ent->d_name, len - elen - 1);
			if (g_hash_table_contains(index, key)) {
				g_free(key);
				continue;
			}
			g_hash_table_insert(index, key,
				g_strdup_printf("%s/%s", dir, ent->d_name));
		}
	}
	closedir(d);
}

static void theme_index(struct theme *theme) {
	theme->index = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
	char dir[1400];
	for (int d = 0; d < theme->dirs_len; d++) {
		for (int r = 0; r < roots_len; r++) {
			snprintf(dir, sizeof(dir), "%s/%s/%s", roots[r], theme->name,
				theme->dirs[d].path);
			index_dir(theme->index, dir);
		}
	}
}

static const char *lookup_in_theme(struct theme *theme, const char *name) {
	if (theme->index == NULL) {
		theme_index(theme);
	}
	return g_hash_table_lookup(theme->index, name);
}

static const char *lookup_chain(const char *theme_name, const char *name,
		const char **visited, int *visited_len) {
	for (int i = 0; i < *visited_len; i++) {
		if (strcmp(visited[i], theme_name) == 0) {
			return NULL;
		}
	}
	if (*visited_len == 32) {
		return NULL;
	}
	visited[(*visited_len)++] = theme_name;

	struct theme *theme = theme_get(theme_name);
	if (theme == NULL) {
		return NULL;
	}
	const char *path = lookup_in_theme(theme, name);
	for (int i = 0; path == NULL && i < theme->inherits_len; i++) {
		path = lookup_chain(theme->inherits[i], name, visited, visited_len);
	}
	return path;
}

/* Guards the theme cache: icons are looked up from the loader thread too */
static pthread_mutex_t lookup_lock = PTHREAD_MUTEX_INITIALIZER;

/* The file for an icon name, or NULL; the caller frees it */
static char *find_icon(const char *theme, const char *name) {
	pthread_mutex_lock(&lookup_lock);
	if (!themes_init) {
		theme_get("hicolor");
	}
	/* The user's theme (and what it inherits), then our own glyphs for
	 * the default tiles, then hicolor where apps install their icons. */
	const char *chain[] = { theme, "cont8nuum", "hicolor" };
	const char *visited[32];
	int visited_len = 0;
	char *found = NULL;
	for (size_t i = 0; found == NULL && i < sizeof(chain) / sizeof(chain[0]); i++) {
		if (chain[i] == NULL || chain[i][0] == '\0') {
			continue;
		}
		const char *path = lookup_chain(chain[i], name, visited, &visited_len);
		found = path ? strdup(path) : NULL;
	}
	pthread_mutex_unlock(&lookup_lock);
	if (found) {
		return found;
	}
	char path[1100];
	for (size_t e = 0; e < sizeof(extensions) / sizeof(extensions[0]); e++) {
		snprintf(path, sizeof(path), "/usr/share/pixmaps/%s.%s", name,
			extensions[e]);
		if (access(path, R_OK) == 0) {
			return strdup(path);
		}
	}
	return NULL;
}

struct c8ui_icon *c8ui_icon_load(const char *theme, const char *name) {
	if (name == NULL || name[0] == '\0') {
		return NULL;
	}
	if (name[0] == '/') {
		return icon_from_file(name);
	}
	char *path = find_icon(theme, name);
	struct c8ui_icon *icon = path ? icon_from_file(path) : NULL;
	free(path);
	return icon;
}

/* Forgets the theme indexes, for after icons are installed or removed */
void c8ui_icon_cache_reset(void) {
	pthread_mutex_lock(&lookup_lock);
	if (themes_init) {
		for (struct theme *theme = themes; theme; theme = theme->next) {
			if (theme->index) {
				g_hash_table_destroy(theme->index);
				theme->index = NULL;
			}
		}
	}
	pthread_mutex_unlock(&lookup_lock);
}

void c8ui_icon_destroy(struct c8ui_icon *icon) {
	if (icon == NULL) {
		return;
	}
	if (icon->png) {
		cairo_surface_destroy(icon->png);
	}
#if C8UI_HAVE_SVG
	if (icon->svg) {
		g_object_unref(icon->svg);
	}
	for (int i = 0; i < 2; i++) {
		if (icon->rasters[i].surface) {
			cairo_surface_destroy(icon->rasters[i].surface);
		}
	}
#endif
	free(icon);
}

void c8ui_icon_get_size(struct c8ui_icon *icon, double *width, double *height) {
	*width = icon->width;
	*height = icon->height;
}

void c8ui_icon_draw(cairo_t *cr, struct c8ui_icon *icon, double x, double y,
		double width, double height) {
#if C8UI_HAVE_SVG
	if (icon->svg) {
		/* Rasterised at the size it lands on screen, so it stays sharp
		 * at any scale, and kept for the next draw at that size */
		double dw = width, dh = height;
		cairo_user_to_device_distance(cr, &dw, &dh);
		int pw = (int)ceil(fabs(dw)), ph = (int)ceil(fabs(dh));
		if (pw <= 0 || ph <= 0) {
			return;
		}
		/* Two sizes are kept: one icon is often shown small in a list
		 * and bigger in a grid at once, and with one slot each of the
		 * two would render it again on every frame */
		struct raster *r = &icon->rasters[0];
		if (r->surface == NULL || r->w != pw || r->h != ph) {
			struct raster other = icon->rasters[1];
			icon->rasters[1] = *r;
			*r = other;
		}
		if (r->surface == NULL || r->w != pw || r->h != ph) {
			if (r->surface) {
				cairo_surface_destroy(r->surface);
			}
			r->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, pw, ph);
			r->w = pw;
			r->h = ph;
			cairo_t *rc = cairo_create(r->surface);
			RsvgRectangle viewport = { 0, 0, pw, ph };
			GError *err = NULL;
			if (!rsvg_handle_render_document(icon->svg, rc, &viewport, &err)) {
				g_clear_error(&err);
			}
			cairo_destroy(rc);
		}
		cairo_save(cr);
		cairo_translate(cr, x, y);
		cairo_scale(cr, width / pw, height / ph);
		cairo_set_source_surface(cr, r->surface, 0, 0);
		cairo_paint(cr);
		cairo_restore(cr);
		return;
	}
#endif
	/* At this size once, then copied (kept.c) */
	c8ui_draw_surface(cr, icon->png, x, y, width, height);
}

void c8ui_icon_draw_fit(cairo_t *cr, struct c8ui_icon *icon, double cx, double cy,
		double size) {
	double s = size / (icon->width > icon->height ? icon->width : icon->height);
	double w = icon->width * s, h = icon->height * s;
	c8ui_icon_draw(cr, icon, cx - w / 2, cy - h / 2, w, h);
}

/*
 * Loading icons in the background. Parsing and rasterising an SVG takes
 * milliseconds, sometimes tens of them; done on the UI thread it stalls
 * every frame and all input. A single worker takes requests one at a
 * time, newest urgent ones first, and hands back an image at the size asked
 * for, which the caller keeps.
 */

struct c8ui_icon_request {
	char *theme, *name;
	int px;
	c8ui_icon_done_fn done;
	void *data;
	cairo_surface_t *result;
	bool cancelled;
	struct c8ui_icon_request *next;
};

static struct {
	bool running, stopping;
	pthread_t thread;
	pthread_cond_t wake;
	struct c8ui_icon_request *queue, *queue_tail; // waiting
	struct c8ui_icon_request *done; // finished, not yet handed back
	struct c8ui_icon_request *current; // being loaded
	int fd; // eventfd: something finished
} loader = { .wake = PTHREAD_COND_INITIALIZER, .fd = -1 };

static pthread_mutex_t loader_lock = PTHREAD_MUTEX_INITIALIZER;

static void request_free(struct c8ui_icon_request *req) {
	if (req->result) {
		cairo_surface_destroy(req->result);
	}
	free(req->theme);
	free(req->name);
	free(req);
}

/* The icon fitted into a px square, keeping its shape */
static cairo_surface_t *rasterise(const char *theme, const char *name, int px) {
	struct c8ui_icon *icon = c8ui_icon_load(theme, name);
	if (icon == NULL) {
		return NULL;
	}
	double s = px / (icon->width > icon->height ? icon->width : icon->height);
	int w = (int)ceil(icon->width * s), h = (int)ceil(icon->height * s);
	cairo_surface_t *out = NULL;
	if (w > 0 && h > 0) {
		out = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h);
		cairo_t *cr = cairo_create(out);
		c8ui_icon_draw(cr, icon, 0, 0, w, h);
		cairo_destroy(cr);
		cairo_surface_flush(out);
	}
	c8ui_icon_destroy(icon);
	return out;
}

static void *loader_main(void *arg) {
	pthread_mutex_lock(&loader_lock);
	for (;;) {
		while (loader.queue == NULL && !loader.stopping) {
			pthread_cond_wait(&loader.wake, &loader_lock);
		}
		if (loader.stopping) {
			break;
		}
		struct c8ui_icon_request *req = loader.queue;
		loader.queue = req->next;
		if (loader.queue == NULL) {
			loader.queue_tail = NULL;
		}
		loader.current = req;
		pthread_mutex_unlock(&loader_lock);

		cairo_surface_t *result = rasterise(req->theme, req->name, req->px);

		pthread_mutex_lock(&loader_lock);
		req->result = result;
		loader.current = NULL;
		req->next = loader.done;
		loader.done = req;
		uint64_t one = 1;
		if (write(loader.fd, &one, sizeof(one)) < 0) {
			/* The counter is already non-zero; the wakeup is pending */
		}
	}
	pthread_mutex_unlock(&loader_lock);
	return NULL;
}

/* On the host's thread: hand back what finished */
void c8ui_icon_loader_dispatch(void) {
	uint64_t n;
	if (loader.fd < 0) {
		return;
	}
	if (read(loader.fd, &n, sizeof(n)) < 0) {
		/* Nothing to read; a spurious wakeup */
	}
	pthread_mutex_lock(&loader_lock);
	struct c8ui_icon_request *list = loader.done;
	loader.done = NULL;
	pthread_mutex_unlock(&loader_lock);
	/* Oldest first, the order they were asked for in */
	struct c8ui_icon_request *rev = NULL;
	while (list) {
		struct c8ui_icon_request *next = list->next;
		list->next = rev;
		rev = list;
		list = next;
	}
	while (rev) {
		struct c8ui_icon_request *req = rev;
		rev = req->next;
		if (!req->cancelled) {
			cairo_surface_t *result = req->result;
			req->result = NULL; // now the caller's
			req->done(req->data, result);
		}
		request_free(req);
	}
}

int c8ui_icon_loader_start(void) {
	if (loader.running) {
		return loader.fd;
	}
	loader.fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
	if (loader.fd < 0) {
		perror("c8ui: eventfd; icons load in the foreground");
		return -1;
	}
	if (pthread_create(&loader.thread, NULL, loader_main, NULL) != 0) {
		fprintf(stderr, "c8ui: cannot start the icon loader; icons load "
			"in the foreground\n");
		close(loader.fd);
		loader.fd = -1;
		return -1;
	}
	loader.running = true;
	return loader.fd;
}

void c8ui_icon_loader_stop(void) {
	if (!loader.running) {
		return;
	}
	pthread_mutex_lock(&loader_lock);
	loader.stopping = true;
	pthread_cond_signal(&loader.wake);
	pthread_mutex_unlock(&loader_lock);
	pthread_join(loader.thread, NULL);
	loader.running = false;
	for (struct c8ui_icon_request *r = loader.queue, *next; r; r = next) {
		next = r->next;
		request_free(r);
	}
	for (struct c8ui_icon_request *r = loader.done, *next; r; r = next) {
		next = r->next;
		request_free(r);
	}
	loader.queue = loader.queue_tail = loader.done = NULL;
	close(loader.fd);
	loader.fd = -1;
}

struct c8ui_icon_request *c8ui_icon_request(const char *theme, const char *name,
		int px, bool urgent, c8ui_icon_done_fn done, void *data) {
	if (!loader.running) {
		/* No thread: load it now, as before */
		done(data, name && name[0] ? rasterise(theme, name, px) : NULL);
		return NULL;
	}
	struct c8ui_icon_request *req = calloc(1, sizeof(*req));
	req->theme = theme ? strdup(theme) : NULL;
	req->name = strdup(name ? name : "");
	req->px = px;
	req->done = done;
	req->data = data;
	pthread_mutex_lock(&loader_lock);
	if (urgent || loader.queue == NULL) {
		/* On screen now: ahead of the background work */
		req->next = loader.queue;
		loader.queue = req;
		if (loader.queue_tail == NULL) {
			loader.queue_tail = req;
		}
	} else {
		loader.queue_tail->next = req;
		loader.queue_tail = req;
	}
	pthread_cond_signal(&loader.wake);
	pthread_mutex_unlock(&loader_lock);
	return req;
}

void c8ui_icon_request_cancel(struct c8ui_icon_request *req) {
	if (req == NULL) {
		return;
	}
	pthread_mutex_lock(&loader_lock);
	/* Still waiting: drop it; loading or loaded: dropped when handed back */
	struct c8ui_icon_request *prev = NULL;
	for (struct c8ui_icon_request *r = loader.queue; r; prev = r, r = r->next) {
		if (r == req) {
			if (prev) {
				prev->next = r->next;
			} else {
				loader.queue = r->next;
			}
			if (loader.queue_tail == r) {
				loader.queue_tail = prev;
			}
			pthread_mutex_unlock(&loader_lock);
			request_free(req);
			return;
		}
	}
	req->cancelled = true;
	pthread_mutex_unlock(&loader_lock);
}
