/*
 * Radar maps: weathersnail's mosaics of the NWS's radars, as ready-made
 * pictures (the light base map, as Windows 8's Weather maps were light)
 * in the web-map projection, with their corners in /api/maps. The newest
 * picture of the region a place is on is downloaded into the cache and
 * decoded on a thread; the place names (/api/basemap/labels.geojson) are
 * drawn once into a picture of their own the map's size, the important
 * ones first and none over another, and laid over it.
 */
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gio/gio.h>
#include <pango/pangocairo.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <c8ui/c8ui.h>
#include "app.h"
#include "json.h"
#include "weather.h"

#define MAPS_MAX_AGE (5 * 60)
#define THEME "light"
#define LABEL_COLOR 0x3b3226
#define STATE_COLOR 0x7a6a55

struct region {
	struct radar_map m;
	char *id; // the picture's (a scan's id)
	char *url, *labels_url;
	bool loading, failed;
	bool labels_loading, labels_done;
};

static struct {
	radar_fn fn;
	void *data;
	char *family;
	GPtrArray *regions; // struct region, from /api/maps
	struct radar_ramp *ramps;
	int ramp_count;
	int64_t fetched;
	bool loading, failed;
	/* A place asked for before the list came */
	bool wanted;
	double want_lat, want_lon;
} rd;

static void tell(void) {
	if (rd.fn) {
		rd.fn(rd.data);
	}
}

static double merc(double lat) {
	double r = lat * G_PI / 180;
	return log(tan(G_PI / 4 + r / 2));
}

void radar_project(const struct radar_map *m, double lat, double lon,
		double *x, double *y) {
	double west = m->west, east = m->east;
	/* Alaska's map runs past -180: a place on the other side of it */
	if (lon > east && lon - 360 >= west) {
		lon -= 360;
	}
	*x = (lon - west) / (east - west) * m->width;
	*y = (merc(m->north) - merc(lat)) / (merc(m->north) - merc(m->south)) *
		m->height;
}

static bool region_has(struct region *r, double lat, double lon) {
	double x, y;
	radar_project(&r->m, lat, lon, &x, &y);
	return x >= 0 && y >= 0 && x < r->m.width && y < r->m.height;
}

static void region_free(gpointer data) {
	struct region *r = data;
	g_free(r->m.region);
	if (r->m.map) {
		cairo_surface_destroy(r->m.map);
	}
	if (r->m.labels) {
		cairo_surface_destroy(r->m.labels);
	}
	g_free(r->id);
	g_free(r->url);
	g_free(r->labels_url);
	g_free(r);
}

/* Decoding, on a thread */

static cairo_surface_t *surface_from_pixbuf(GdkPixbuf *pb) {
	int w = gdk_pixbuf_get_width(pb), h = gdk_pixbuf_get_height(pb);
	int n = gdk_pixbuf_get_n_channels(pb);
	bool alpha = gdk_pixbuf_get_has_alpha(pb);
	int src_stride = gdk_pixbuf_get_rowstride(pb);
	const guchar *src = gdk_pixbuf_read_pixels(pb);
	cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_RGB24, w, h);
	if (cairo_surface_status(s) != CAIRO_STATUS_SUCCESS) {
		return s;
	}
	cairo_surface_flush(s);
	unsigned char *dst = cairo_image_surface_get_data(s);
	int stride = cairo_image_surface_get_stride(s);
	for (int y = 0; y < h; y++) {
		const guchar *p = src + y * src_stride;
		uint32_t *q = (uint32_t *)(dst + y * stride);
		for (int x = 0; x < w; x++, p += n) {
			/* The base map is opaque: a see-through pixel shows white */
			uint32_t a = alpha ? p[3] : 255;
			uint32_t r = (p[0] * a + 255 * (255 - a)) / 255;
			uint32_t g = (p[1] * a + 255 * (255 - a)) / 255;
			uint32_t b = (p[2] * a + 255 * (255 - a)) / 255;
			q[x] = 0xff000000 | r << 16 | g << 8 | b;
		}
	}
	cairo_surface_mark_dirty(s);
	return s;
}

static void decode_thread(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	GdkPixbuf *pb = gdk_pixbuf_new_from_file(data, NULL);
	if (pb == NULL) {
		g_task_return_pointer(task, NULL, NULL);
		return;
	}
	cairo_surface_t *s = surface_from_pixbuf(pb);
	g_object_unref(pb);
	g_task_return_pointer(task, s, (GDestroyNotify)cairo_surface_destroy);
}

struct decode {
	char *region, *id;
};

static struct region *find_region(const char *name) {
	for (guint i = 0; rd.regions && i < rd.regions->len; i++) {
		struct region *r = rd.regions->pdata[i];
		if (strcmp(r->m.region, name) == 0) {
			return r;
		}
	}
	return NULL;
}

static void load_labels(struct region *r);

static void decoded(GObject *source, GAsyncResult *res, gpointer data) {
	struct decode *d = data;
	cairo_surface_t *s = g_task_propagate_pointer(G_TASK(res), NULL);
	struct region *r = find_region(d->region);
	if (r && g_strcmp0(r->id, d->id) == 0) {
		r->loading = false;
		if (s && cairo_surface_status(s) == CAIRO_STATUS_SUCCESS) {
			if (r->m.map) {
				cairo_surface_destroy(r->m.map);
			}
			r->m.map = s;
			s = NULL;
			load_labels(r);
			tell();
		} else {
			r->failed = true;
			tell();
		}
	}
	if (s) {
		cairo_surface_destroy(s);
	}
	g_free(d->region);
	g_free(d->id);
	g_free(d);
}

static char *picture_path(struct region *r) {
	char *name = g_strdup_printf("radar-%s-%s.png", r->m.region, r->id);
	char *path = ws_cache_path(name);
	g_free(name);
	return path;
}

/* Only the newest picture of each region is kept */
static void forget_old_pictures(struct region *r) {
	char *dir = ws_cache_path("");
	char *prefix = g_strdup_printf("radar-%s-", r->m.region);
	char *keep = g_strdup_printf("radar-%s-%s.png", r->m.region, r->id);
	GDir *gd = g_dir_open(dir, 0, NULL);
	const char *name;
	while (gd && (name = g_dir_read_name(gd))) {
		if (g_str_has_prefix(name, prefix) && strcmp(name, keep) != 0) {
			char *path = g_build_filename(dir, name, NULL);
			g_unlink(path);
			g_free(path);
		}
	}
	if (gd) {
		g_dir_close(gd);
	}
	g_free(keep);
	g_free(prefix);
	g_free(dir);
}

static void decode(struct region *r) {
	struct decode *d = g_new0(struct decode, 1);
	d->region = g_strdup(r->m.region);
	d->id = g_strdup(r->id);
	GTask *task = g_task_new(NULL, NULL, decoded, d);
	g_task_set_task_data(task, picture_path(r), g_free);
	g_task_run_in_thread(task, decode_thread);
	g_object_unref(task);
}

static void downloaded(int status, const char *body, void *data) {
	struct decode *d = data;
	struct region *r = find_region(d->region);
	if (r && g_strcmp0(r->id, d->id) == 0) {
		if (status == 200) {
			forget_old_pictures(r);
			decode(r);
		} else {
			r->loading = false;
			r->failed = true;
			tell();
		}
	}
	g_free(d->region);
	g_free(d->id);
	g_free(d);
}

static void fetch_picture(struct region *r) {
	/* One that failed is tried again when there's a newer one */
	if (r->loading || r->url == NULL || r->failed) {
		return;
	}
	char *path = picture_path(r);
	bool cached = g_file_test(path, G_FILE_TEST_EXISTS);
	if (!cached && rd.fetched == 0) {
		/* The list is the cache's: a newer one is on its way */
		g_free(path);
		return;
	}
	r->loading = true;
	if (cached) {
		decode(r);
	} else {
		struct decode *d = g_new0(struct decode, 1);
		d->region = g_strdup(r->m.region);
		d->id = g_strdup(r->id);
		char *url = g_strconcat(API, r->url, NULL);
		ws_download(url, path, downloaded, d);
		g_free(url);
	}
	g_free(path);
}

/* Place names */

struct label {
	const char *name;
	double x, y;
	bool state;
	int rank;
};

static int label_cmp(gconstpointer a, gconstpointer b) {
	const struct label *x = a, *y = b;
	/* States first (they're big and few), then the most important towns */
	if (x->state != y->state) {
		return x->state ? -1 : 1;
	}
	return x->rank - y->rank;
}

static bool overlaps(GArray *taken, double x, double y, double w, double h) {
	for (guint i = 0; i < taken->len / 4; i++) { // four doubles a box
		double *r = &g_array_index(taken, double, i * 4);
		if (x < r[0] + r[2] && r[0] < x + w && y < r[1] + r[3] && r[1] < y + h) {
			return true;
		}
	}
	return false;
}

static cairo_surface_t *draw_labels(struct region *r, struct json *geo) {
	GArray *labels = g_array_new(FALSE, FALSE, sizeof(struct label));
	struct json *features = json_get(geo, "features");
	for (struct json *f = features ? features->child : NULL; f; f = f->next) {
		struct json *props = json_get(f, "properties");
		struct json *coords = json_get(json_get(f, "geometry"), "coordinates");
		const char *name = json_str(json_get(props, "name"), NULL);
		int min_zoom = (int)json_num(json_get(props, "min_zoom"), 99);
		if (name == NULL || json_length(coords) < 2 || min_zoom > r->m.zoom) {
			continue;
		}
		struct label l = {
			.name = name,
			.state = strcmp(json_str(json_get(props, "kind"), ""), "state") == 0,
			.rank = (int)json_num(json_get(props, "rank"), 1000),
		};
		radar_project(&r->m, json_num(json_at(coords, 1), 0),
			json_num(json_at(coords, 0), 0), &l.x, &l.y);
		if (l.x < 0 || l.y < 0 || l.x >= r->m.width || l.y >= r->m.height) {
			continue;
		}
		g_array_append_val(labels, l);
	}
	g_array_sort(labels, label_cmp);
	cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		r->m.width, r->m.height);
	cairo_t *cr = cairo_create(s);
	PangoLayout *layout = pango_cairo_create_layout(cr);
	PangoFontDescription *town = pango_font_description_from_string(
		rd.family ? rd.family : "sans");
	pango_font_description_set_absolute_size(town, 11 * PANGO_SCALE);
	PangoFontDescription *state = pango_font_description_copy(town);
	pango_font_description_set_absolute_size(state, 13 * PANGO_SCALE);
	pango_font_description_set_weight(state, PANGO_WEIGHT_SEMIBOLD);
	GArray *taken = g_array_new(FALSE, FALSE, sizeof(double));
	cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
	for (guint i = 0; i < labels->len; i++) {
		struct label *l = &g_array_index(labels, struct label, i);
		char *text = l->state ? g_utf8_strup(l->name, -1) : g_strdup(l->name);
		pango_layout_set_font_description(layout, l->state ? state : town);
		pango_layout_set_text(layout, text, -1);
		int pw, ph;
		pango_layout_get_pixel_size(layout, &pw, &ph);
		/* States centred on their point, towns beside their dot */
		double x = l->state ? l->x - pw / 2.0 : l->x + 5;
		double y = l->y - ph / 2.0;
		double box[4] = { x - 3, y - 1, pw + 6 + (l->state ? 0 : 8), ph + 2 };
		if (!l->state) {
			box[0] -= 8;
		}
		if (overlaps(taken, box[0], box[1], box[2], box[3])) {
			g_free(text);
			continue;
		}
		g_array_append_vals(taken, box, 4);
		if (!l->state) {
			cairo_arc(cr, l->x, l->y, 2.5, 0, 2 * G_PI);
			cairo_set_source_rgba(cr, 1, 1, 1, 0.9);
			cairo_set_line_width(cr, 2);
			cairo_stroke_preserve(cr);
			c8ui_set_source(cr, LABEL_COLOR, 1);
			cairo_fill(cr);
		}
		cairo_move_to(cr, x, y);
		pango_cairo_layout_path(cr, layout);
		cairo_set_source_rgba(cr, 1, 1, 1, 0.85);
		cairo_set_line_width(cr, 3);
		cairo_stroke(cr);
		cairo_move_to(cr, x, y);
		c8ui_set_source(cr, l->state ? STATE_COLOR : LABEL_COLOR, 1);
		pango_cairo_show_layout(cr, layout);
		cairo_new_path(cr); // or the next dot's arc joins this point
		g_free(text);
	}
	g_array_unref(taken);
	pango_font_description_free(town);
	pango_font_description_free(state);
	g_object_unref(layout);
	cairo_destroy(cr);
	g_array_unref(labels);
	return s;
}

struct labels_req {
	char *region;
	char *path;
};

static void take_labels(struct region *r, const char *text) {
	struct json *geo = text ? json_parse(text) : NULL;
	if (geo && r->m.map) {
		if (r->m.labels) {
			cairo_surface_destroy(r->m.labels);
		}
		r->m.labels = draw_labels(r, geo);
		r->labels_done = true;
	}
	json_free(geo);
}

static void got_labels(int status, const char *body, void *data) {
	struct labels_req *l = data;
	struct region *r = find_region(l->region);
	if (r) {
		r->labels_loading = false;
		if (status == 200 && body) {
			char *dir = g_path_get_dirname(l->path);
			g_mkdir_with_parents(dir, 0700);
			g_file_set_contents(l->path, body, -1, NULL);
			g_free(dir);
			take_labels(r, body);
			tell();
		}
	}
	g_free(l->region);
	g_free(l->path);
	g_free(l);
}

/* They change only when the base map is rebuilt: kept by its address */
static void load_labels(struct region *r) {
	if (r->labels_done || r->labels_loading || r->labels_url == NULL) {
		return;
	}
	char *sum = g_compute_checksum_for_string(G_CHECKSUM_SHA1, r->labels_url,
		-1);
	char *name = g_strdup_printf("labels-%.12s.json", sum);
	char *path = ws_cache_path(name);
	g_free(name);
	g_free(sum);
	char *text = NULL;
	if (g_file_get_contents(path, &text, NULL, NULL)) {
		take_labels(r, text);
		g_free(text);
		g_free(path);
		return;
	}
	r->labels_loading = true;
	struct labels_req *l = g_new0(struct labels_req, 1);
	l->region = g_strdup(r->m.region);
	l->path = path;
	char *url = g_strconcat(API, r->labels_url, NULL);
	ws_http("GET", url, NULL, NULL, got_labels, l);
	g_free(url);
}

/* The list of maps */

static uint32_t hex(const char *s) {
	return s && s[0] == '#' ? (uint32_t)strtoul(s + 1, NULL, 16) : 0;
}

static void take_ramps(struct json *legend) {
	for (int i = 0; i < rd.ramp_count; i++) {
		g_free(rd.ramps[i].label);
		g_free(rd.ramps[i].stops);
	}
	g_free(rd.ramps);
	rd.ramp_count = 0;
	rd.ramps = g_new0(struct radar_ramp, json_length(legend) + 1);
	for (struct json *k = legend ? legend->child : NULL; k; k = k->next) {
		struct json *stops = json_get(k, "stops");
		int n = json_length(stops);
		if (n == 0) {
			continue;
		}
		struct radar_ramp *ramp = &rd.ramps[rd.ramp_count++];
		ramp->label = g_strdup(json_str(json_get(k, "label"), k->key));
		ramp->stops = g_new0(struct radar_stop, n);
		ramp->count = n;
		for (int i = 0; i < n; i++) {
			struct json *s = json_at(stops, i);
			ramp->stops[i].dbz = json_num(json_at(s, 0), 0);
			ramp->stops[i].color = hex(json_str(json_at(s, 1), NULL));
		}
	}
}

static void want(double lat, double lon);

static bool take_maps(const char *text) {
	struct json *root = text ? json_parse(text) : NULL;
	struct json *regions = json_get(root, "regions");
	if (regions == NULL || regions->type != JSON_OBJECT) {
		json_free(root);
		return false;
	}
	if (rd.regions == NULL) {
		rd.regions = g_ptr_array_new_with_free_func(region_free);
	}
	for (struct json *k = regions->child; k; k = k->next) {
		struct json *bounds = json_get(k, "bounds");
		struct json *size = json_get(k, "size");
		const char *id = json_str(json_get(k, "id"), NULL);
		const char *url = json_str(json_get(json_get(k, "urls"), THEME), NULL);
		if (!ws_id_ok(k->key) || json_length(bounds) != 4 ||
				json_length(size) != 2 || !ws_id_ok(id) || url == NULL) {
			continue;
		}
		struct region *r = find_region(k->key);
		if (r == NULL) {
			r = g_new0(struct region, 1);
			r->m.region = g_strdup(k->key);
			g_ptr_array_add(rd.regions, r);
		}
		int w = (int)json_num(json_at(size, 0), 0);
		int h = (int)json_num(json_at(size, 1), 0);
		if (r->m.width != w || r->m.height != h) {
			/* Another base map: its names were placed on the old one */
			if (r->m.labels) {
				cairo_surface_destroy(r->m.labels);
				r->m.labels = NULL;
			}
			r->labels_done = false;
			if (r->m.map) {
				cairo_surface_destroy(r->m.map);
				r->m.map = NULL;
			}
		}
		r->m.west = json_num(json_at(bounds, 0), 0);
		r->m.south = json_num(json_at(bounds, 1), 0);
		r->m.east = json_num(json_at(bounds, 2), 0);
		r->m.north = json_num(json_at(bounds, 3), 0);
		r->m.width = w;
		r->m.height = h;
		r->m.zoom = (int)json_num(json_get(k, "zoom"), 6);
		const char *labels = json_str(json_get(k, "labels_url"), NULL);
		if (g_strcmp0(r->labels_url, labels) != 0) {
			g_free(r->labels_url);
			r->labels_url = g_strdup(labels);
			r->labels_done = false;
		}
		if (g_strcmp0(r->id, id) != 0) {
			g_free(r->id);
			r->id = g_strdup(id);
			g_free(r->url);
			r->url = g_strdup(url);
			r->failed = false;
			GDateTime *t = g_date_time_new_from_iso8601(
				json_str(json_get(k, "time"), ""), NULL);
			r->m.time = t ? g_date_time_to_unix(t) : 0;
			if (t) {
				g_date_time_unref(t);
			}
			/* A newer one: fetched if the old one was being shown */
			if (r->m.map) {
				fetch_picture(r);
			}
		}
	}
	take_ramps(json_get(root, "legend"));
	json_free(root);
	return true;
}

static void got_maps(int status, const char *body, void *data) {
	rd.loading = false;
	if (status == 200 && take_maps(body)) {
		rd.fetched = g_get_real_time() / G_USEC_PER_SEC;
		rd.failed = false;
		char *path = ws_cache_path("maps.json");
		g_file_set_contents(path, body, -1, NULL);
		g_free(path);
		if (rd.wanted) {
			want(rd.want_lat, rd.want_lon);
		}
	} else {
		rd.failed = true;
	}
	tell();
}

void radar_refresh(void) {
	if (rd.loading) {
		return;
	}
	rd.loading = true;
	ws_http("GET", API "/api/maps", NULL, NULL, got_maps, NULL);
}

static void want(double lat, double lon) {
	for (guint i = 0; rd.regions && i < rd.regions->len; i++) {
		struct region *r = rd.regions->pdata[i];
		if (region_has(r, lat, lon)) {
			if (r->m.map == NULL) {
				fetch_picture(r);
			}
			return;
		}
	}
}

const struct radar_map *radar_for(double lat, double lon) {
	int64_t now = g_get_real_time() / G_USEC_PER_SEC;
	if (now - rd.fetched > MAPS_MAX_AGE) {
		radar_refresh();
	}
	rd.wanted = true;
	rd.want_lat = lat;
	rd.want_lon = lon;
	for (guint i = 0; rd.regions && i < rd.regions->len; i++) {
		struct region *r = rd.regions->pdata[i];
		if (region_has(r, lat, lon)) {
			if (r->m.map == NULL) {
				fetch_picture(r);
			}
			return r->m.map ? &r->m : NULL;
		}
	}
	return NULL;
}

bool radar_failed(double lat, double lon) {
	if (rd.regions == NULL) {
		return rd.failed;
	}
	for (guint i = 0; i < rd.regions->len; i++) {
		struct region *r = rd.regions->pdata[i];
		if (region_has(r, lat, lon)) {
			return r->failed && r->m.map == NULL;
		}
	}
	return true; // on no map
}

const struct radar_ramp *radar_ramps(int *count) {
	*count = rd.ramp_count;
	return rd.ramps;
}

void radar_init(radar_fn fn, void *data, const char *family) {
	rd.fn = fn;
	rd.data = data;
	rd.family = g_strdup(family);
	/* What the cache has: the pictures it names are there too */
	char *path = ws_cache_path("maps.json"), *text = NULL;
	if (g_file_get_contents(path, &text, NULL, NULL)) {
		take_maps(text);
		g_free(text);
	}
	g_free(path);
}
