/*
 * The weather of the places: weathersnail's forecast (the NWS's week, then
 * the National Blend's days, and the next 48 hours), what the nearest
 * station says now, and the NWS alerts whose areas the place is in. Each
 * answer is kept in the cache and read from there first.
 *
 * Answers come back to a place by its id: a place removed meanwhile is
 * simply not found.
 */
#include <gio/gio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "json.h"
#include "weather.h"

#define ALERTS_MAX_AGE (5 * 60)
#define CONDITIONS_BATCH 50 // the most /api/conditions takes
#define RAIN_RADIUS_KM 10 // what's falling: looked for this far round

struct ws_place *ws_preview;

struct listener {
	ws_change_fn fn;
	void *data;
};
static GArray *listeners; // struct listener

static GPtrArray *alerts; // struct ws_alert, every one in force
static int64_t alerts_fetched;
static bool alerts_loading;

void ws_on_change(ws_change_fn fn, void *data) {
	if (listeners == NULL) {
		listeners = g_array_new(FALSE, FALSE, sizeof(struct listener));
	}
	struct listener l = { fn, data };
	g_array_append_val(listeners, l);
}

static void ws_changed(struct ws_place *place) {
	for (guint i = 0; listeners && i < listeners->len; i++) {
		struct listener *l = &g_array_index(listeners, struct listener, i);
		l->fn(place, l->data);
	}
}

/* A place still about, by id: a favourite (ours or the account's) or the
 * one being previewed */
static struct ws_place *lookup(const char *id) {
	struct ws_place *p = ws_place_find(id);
	if (p == NULL && ws_local_places() != ws_places) {
		for (guint i = 0; i < ws_local_places()->len; i++) {
			struct ws_place *q = ws_local_places()->pdata[i];
			if (strcmp(q->id, id) == 0) {
				p = q;
			}
		}
	}
	if (p == NULL && ws_preview && strcmp(ws_preview->id, id) == 0) {
		p = ws_preview;
	}
	return p;
}

static int64_t iso_time(const char *s) {
	if (s == NULL) {
		return 0;
	}
	GDateTime *dt = g_date_time_new_from_iso8601(s, NULL);
	if (dt == NULL) {
		return 0;
	}
	int64_t t = g_date_time_to_unix(dt);
	g_date_time_unref(dt);
	return t;
}

static double num_or_nan(struct json *j) {
	return j && (j->type == JSON_NUMBER || j->type == JSON_STRING) ?
		json_num(j, NAN) : NAN;
}

static char *str_or_null(struct json *j) {
	const char *s = json_str(j, NULL);
	return s && s[0] ? g_strdup(s) : NULL;
}

static char *units_name(void) {
	return g_strdup(ws_settings.units == WS_CELSIUS ? "si" : "us");
}

static void save_cache(const char *name, const char *text) {
	char *path = ws_cache_path(name);
	char *dir = g_path_get_dirname(path);
	g_mkdir_with_parents(dir, 0700);
	g_file_set_contents(path, text, -1, NULL);
	g_free(dir);
	g_free(path);
}

static char *read_cache(const char *name) {
	char *path = ws_cache_path(name), *text = NULL;
	g_file_get_contents(path, &text, NULL, NULL);
	g_free(path);
	return text;
}

/* Forecasts */

static void forecast_free(struct ws_forecast *f) {
	if (f == NULL) {
		return;
	}
	for (guint i = 0; i < f->days->len; i++) {
		struct ws_day *d = &g_array_index(f->days, struct ws_day, i);
		g_free(d->date);
		g_free(d->name);
		g_free(d->icon);
		g_free(d->summary);
		g_free(d->day_text);
		g_free(d->night_text);
	}
	for (guint i = 0; i < f->hours->len; i++) {
		struct ws_hour *h = &g_array_index(f->hours, struct ws_hour, i);
		g_date_time_unref(h->time);
		g_free(h->wind_dir);
		g_free(h->summary);
		g_free(h->icon);
	}
	g_array_unref(f->days);
	g_array_unref(f->hours);
	g_free(f->office);
	g_free(f->time_zone);
	g_free(f);
}

static struct ws_forecast *forecast_parse(const char *text) {
	struct json *root = text ? json_parse(text) : NULL;
	struct json *days = json_get(root, "days");
	if (root == NULL || days == NULL || days->type != JSON_ARRAY) {
		json_free(root);
		return NULL;
	}
	struct ws_forecast *f = g_new0(struct ws_forecast, 1);
	f->days = g_array_new(FALSE, TRUE, sizeof(struct ws_day));
	f->hours = g_array_new(FALSE, TRUE, sizeof(struct ws_hour));
	for (int i = 0; i < json_length(days); i++) {
		struct json *j = json_at(days, i);
		struct ws_day d = {
			.date = str_or_null(json_get(j, "date")),
			.name = str_or_null(json_get(j, "name")),
			.high = num_or_nan(json_get(j, "high_c")),
			.low = num_or_nan(json_get(j, "low_c")),
			.pop = (int)json_num(json_get(j, "pop"), 0),
			.icon = str_or_null(json_get(j, "icon")),
			.summary = str_or_null(json_get(j, "short")),
			.day_text = str_or_null(json_get(j, "day")),
			.night_text = str_or_null(json_get(j, "night")),
		};
		if (d.date == NULL) {
			g_free(d.name);
			g_free(d.icon);
			g_free(d.summary);
			g_free(d.day_text);
			g_free(d.night_text);
			continue;
		}
		g_array_append_val(f->days, d);
	}
	struct json *hours = json_get(root, "hourly");
	int64_t now = g_get_real_time() / G_USEC_PER_SEC;
	for (int i = 0; i < json_length(hours); i++) {
		struct json *j = json_at(hours, i);
		GDateTime *t = g_date_time_new_from_iso8601(
			json_str(json_get(j, "time"), ""), NULL);
		if (t == NULL) {
			continue;
		}
		/* An hour that's over: the cache can be a while old */
		if (g_date_time_to_unix(t) + 3600 <= now) {
			g_date_time_unref(t);
			continue;
		}
		struct ws_hour h = {
			.time = t,
			.temp = num_or_nan(json_get(j, "temp_c")),
			.pop = (int)json_num(json_get(j, "pop"), 0),
			.wind_kmh = num_or_nan(json_get(j, "wind_kmh")),
			.wind_dir = str_or_null(json_get(j, "wind_dir")),
			.summary = str_or_null(json_get(j, "short")),
			.icon = str_or_null(json_get(j, "icon")),
		};
		g_array_append_val(f->hours, h);
	}
	f->office = str_or_null(json_get(root, "office"));
	f->time_zone = str_or_null(json_get(root, "time_zone"));
	f->updated = iso_time(json_str(json_get(root, "updated"), NULL));
	json_free(root);
	return f;
}

static char *forecast_cache_name(struct ws_place *p) {
	char *u = units_name();
	char *name = g_strdup_printf("forecast-%s-%s.json", p->id, u);
	g_free(u);
	return name;
}

/* Conditions */

static void now_free(struct ws_now *n) {
	if (n == NULL) {
		return;
	}
	g_free(n->weather);
	g_free(n->trend);
	g_free(n->station);
	g_free(n->precip);
	g_free(n->intensity);
	g_free(n);
}

static struct ws_now *now_parse(struct json *j) {
	if (j == NULL || j->type != JSON_OBJECT) {
		return NULL;
	}
	struct ws_now *n = g_new0(struct ws_now, 1);
	n->temp = num_or_nan(json_get(j, "temp_c"));
	n->dewpoint = num_or_nan(json_get(j, "dewpoint_c"));
	n->humidity = num_or_nan(json_get(j, "rh"));
	n->wind_dir = num_or_nan(json_get(j, "wind_dir"));
	n->wind_kt = num_or_nan(json_get(j, "wind_kt"));
	n->gust_kt = num_or_nan(json_get(j, "gust_kt"));
	n->weather = str_or_null(json_get(j, "weather"));
	struct json *pr = json_get(j, "pressure");
	n->pressure = num_or_nan(json_get(pr, "hpa"));
	n->trend = str_or_null(json_get(pr, "trend"));
	struct json *src = json_get(j, "source");
	n->station = str_or_null(json_get(src, "name"));
	n->time = iso_time(json_str(json_get(src, "time"), NULL));
	struct json *area = json_get(json_get(j, "precip"), "area");
	n->precip = str_or_null(json_get(area, "label"));
	n->intensity = str_or_null(json_get(area, "intensity"));
	return n;
}

static char *now_cache_name(struct ws_place *p) {
	return g_strdup_printf("now-%s.json", p->id);
}

/* Alerts */

static void alert_free(gpointer data) {
	struct ws_alert *a = data;
	g_free(a->id);
	g_free(a->event);
	g_free(a->headline);
	g_free(a->severity);
	g_free(a->sender);
	g_free(a->area);
	if (a->rings) {
		g_ptr_array_unref(a->rings);
	}
	g_free(a);
}

/* A shape is polygons of rings, each ring thousandths of a degree: the
 * first point, then each one's step from the one before */
static GPtrArray *decode_shape(struct json *shape) {
	GPtrArray *rings = g_ptr_array_new_with_free_func(
		(GDestroyNotify)g_array_unref);
	bool nested = shape->type == JSON_ARRAY;
	for (struct json *poly = nested ? shape->child : NULL; poly;
			poly = poly->next) {
		for (struct json *ring = poly->type == JSON_ARRAY ? poly->child :
				NULL; ring; ring = ring->next) {
			int n = ring->type == JSON_ARRAY ? json_length(ring) : 0;
			if (n < 6) {
				continue;
			}
			/* Floats: a thousandth of a degree fits, and every alert in
			 * the country is kept, so their size is what we hold */
			GArray *pts = g_array_sized_new(FALSE, FALSE, sizeof(float), n);
			double lon = 0, lat = 0;
			for (struct json *v = ring->child; v && v->next;
					v = v->next->next) {
				lon += json_num(v, 0);
				lat += json_num(v->next, 0);
				float xy[2] = { (float)(lon / 1000), (float)(lat / 1000) };
				g_array_append_vals(pts, xy, 2);
			}
			g_ptr_array_add(rings, pts);
		}
	}
	return rings;
}

/* Even-odd over every ring: holes come out, and the rare overlap of two
 * polygons of one alert is no matter */
static bool alert_covers(struct ws_alert *a, double lat, double lon) {
	bool in = false;
	for (guint r = 0; a->rings && r < a->rings->len; r++) {
		GArray *pts = a->rings->pdata[r];
		int n = (int)pts->len / 2;
		const float *p = (const float *)pts->data;
		for (int i = 0, j = n - 1; i < n; j = i++) {
			double xi = p[2 * i], yi = p[2 * i + 1];
			double xj = p[2 * j], yj = p[2 * j + 1];
			if ((yi > lat) != (yj > lat) &&
					lon < (xj - xi) * (lat - yi) / (yj - yi) + xi) {
				in = !in;
			}
		}
	}
	return in;
}

static bool parse_hex(const char *s, uint32_t *rgb) {
	if (s == NULL || s[0] != '#' || strlen(s) != 7) {
		return false;
	}
	char *end;
	unsigned long v = strtoul(s + 1, &end, 16);
	if (*end) {
		return false;
	}
	*rgb = (uint32_t)v;
	return true;
}

static int severity_rank(const char *s) {
	static const char *const order[] = { "Extreme", "Severe", "Moderate",
		"Minor" };
	for (int i = 0; i < 4; i++) {
		if (g_strcmp0(s, order[i]) == 0) {
			return i;
		}
	}
	return 4;
}

static int alert_cmp(gconstpointer a, gconstpointer b) {
	const struct ws_alert *x = *(struct ws_alert *const *)a;
	const struct ws_alert *y = *(struct ws_alert *const *)b;
	int d = severity_rank(x->severity) - severity_rank(y->severity);
	return d ? d : (x->onset > y->onset) - (x->onset < y->onset);
}

static void match_alerts(struct ws_place *p) {
	if (p->alerts) {
		g_ptr_array_unref(p->alerts);
	}
	p->alerts = g_ptr_array_new();
	int64_t now = g_get_real_time() / G_USEC_PER_SEC;
	GHashTable *seen = g_hash_table_new(g_str_hash, g_str_equal);
	for (guint i = 0; alerts && i < alerts->len; i++) {
		struct ws_alert *a = alerts->pdata[i];
		if (a->cancelled || (a->ends && a->ends < now) || !a->event ||
				!alert_covers(a, p->lat, p->lon)) {
			continue;
		}
		/* An update of an alert comes as another one: show the event once */
		if (g_hash_table_contains(seen, a->event)) {
			continue;
		}
		g_hash_table_add(seen, a->event);
		g_ptr_array_add(p->alerts, a);
	}
	g_hash_table_unref(seen);
	g_ptr_array_sort(p->alerts, alert_cmp);
}

static void match_everywhere(void) {
	for (guint i = 0; i < ws_places->len; i++) {
		match_alerts(ws_places->pdata[i]);
	}
	if (ws_preview) {
		match_alerts(ws_preview);
	}
}

static bool alerts_parse(const char *text) {
	struct json *root = text ? json_parse(text) : NULL;
	struct json *list = json_get(root, "alerts");
	struct json *shapes = json_get(root, "shapes");
	if (list == NULL || list->type != JSON_ARRAY) {
		json_free(root);
		return false;
	}
	GPtrArray *fresh = g_ptr_array_new_with_free_func(alert_free);
	GHashTable *replaced = g_hash_table_new(g_str_hash, g_str_equal);
	/* Thousands of alerts, each naming one of thousands of shapes: looked
	 * up by walking the tree, that was most of a second every time */
	GHashTable *by_key = g_hash_table_new(g_str_hash, g_str_equal);
	for (struct json *sh = shapes && shapes->type == JSON_OBJECT ?
			shapes->child : NULL; sh; sh = sh->next) {
		if (sh->key) {
			g_hash_table_insert(by_key, sh->key, sh);
		}
	}
	for (struct json *j = list->child; j; j = j->next) {
		if (json_bool(json_get(j, "marine"))) {
			continue;
		}
		struct json *shape = g_hash_table_lookup(by_key,
			json_str(json_get(j, "shape"), ""));
		if (shape == NULL) {
			continue; // nowhere to place it
		}
		struct ws_alert *a = g_new0(struct ws_alert, 1);
		a->id = str_or_null(json_get(j, "id"));
		a->event = str_or_null(json_get(j, "event"));
		a->headline = str_or_null(json_get(j, "headline"));
		a->severity = str_or_null(json_get(j, "severity"));
		a->sender = str_or_null(json_get(j, "sender"));
		a->area = str_or_null(json_get(j, "area"));
		if (!parse_hex(json_str(json_get(j, "color"), NULL), &a->color)) {
			a->color = 0xffa500;
		}
		a->onset = iso_time(json_str(json_get(j, "onset"), NULL));
		a->ends = iso_time(json_str(json_get(j, "ends"), NULL));
		a->rings = decode_shape(shape);
		/* What a newer one replaces is over */
		struct json *refs = json_get(j, "references");
		for (struct json *rj = refs && refs->type == JSON_ARRAY ?
				refs->child : NULL; rj; rj = rj->next) {
			const char *ref = json_str(rj, NULL);
			if (ref == NULL) {
				ref = json_str(json_get(rj, "id"), NULL);
			}
			if (ref) {
				g_hash_table_add(replaced, (gpointer)ref);
			}
		}
		g_ptr_array_add(fresh, a);
	}
	for (guint i = 0; i < fresh->len; i++) {
		struct ws_alert *a = fresh->pdata[i];
		a->cancelled = a->id && g_hash_table_contains(replaced, a->id);
	}
	g_hash_table_unref(replaced);
	g_hash_table_unref(by_key);
	json_free(root);
	GPtrArray *old = alerts;
	alerts = fresh;
	match_everywhere(); // before the old ones go: places point at them
	if (old) {
		g_ptr_array_unref(old);
	}
	return true;
}

static void got_alerts(int status, const char *body, void *data) {
	alerts_loading = false;
	if (status == 200 && alerts_parse(body)) {
		alerts_fetched = g_get_real_time() / G_USEC_PER_SEC;
		save_cache("alerts.json", body);
		ws_changed(NULL);
	}
}

static void refresh_alerts(bool force) {
	int64_t now = g_get_real_time() / G_USEC_PER_SEC;
	if (alerts_loading || (!force && now - alerts_fetched < ALERTS_MAX_AGE)) {
		return;
	}
	alerts_loading = true;
	ws_http("GET", API "/api/alerts?compact=true", NULL, NULL, got_alerts,
		NULL);
}

static void load_cached_alerts(void) {
	if (alerts) {
		return;
	}
	char *text = read_cache("alerts.json");
	if (text) {
		alerts_parse(text);
		/* Its age is the file's: fetched again once that's too old */
		char *path = ws_cache_path("alerts.json");
		GStatBuf st;
		if (g_stat(path, &st) == 0) {
			alerts_fetched = st.st_mtime;
		}
		g_free(path);
	}
	g_free(text);
}

/* Loading and refreshing */

void ws_forget(struct ws_place *p) {
	forecast_free(p->forecast);
	p->forecast = NULL;
	now_free(p->now);
	p->now = NULL;
	if (p->alerts) {
		g_ptr_array_unref(p->alerts);
		p->alerts = NULL;
	}
}

void ws_load_cached(struct ws_place *p) {
	load_cached_alerts();
	char *name = forecast_cache_name(p);
	char *text = read_cache(name);
	struct ws_forecast *f = forecast_parse(text);
	if (f) {
		forecast_free(p->forecast);
		p->forecast = f;
	}
	g_free(text);
	g_free(name);
	name = now_cache_name(p);
	text = read_cache(name);
	struct json *j = text ? json_parse(text) : NULL;
	struct ws_now *n = now_parse(j);
	if (n) {
		now_free(p->now);
		p->now = n;
	}
	json_free(j);
	g_free(text);
	g_free(name);
	match_alerts(p);
}

struct req {
	char *id;
	char *units; // what the forecast was asked in
};

static void req_free(struct req *r) {
	g_free(r->id);
	g_free(r->units);
	g_free(r);
}

static void got_forecast(int status, const char *body, void *data) {
	struct req *r = data;
	struct ws_place *p = lookup(r->id);
	char *units = units_name();
	bool current = strcmp(units, r->units) == 0;
	g_free(units);
	if (p == NULL || !current) {
		/* Gone, or asked in other units: another answer is on its way */
		if (p && !current) {
			p->loading = false;
		}
		req_free(r);
		return;
	}
	p->loading = false;
	struct ws_forecast *f = status == 200 ? forecast_parse(body) : NULL;
	g_clear_pointer(&p->error, g_free);
	if (f) {
		forecast_free(p->forecast);
		p->forecast = f;
		p->fetched = g_get_real_time() / G_USEC_PER_SEC;
		char *name = forecast_cache_name(p);
		save_cache(name, body);
		g_free(name);
	} else if (status == 404) {
		p->error = g_strdup("There's no forecast for this place. "
			"Weather's forecasts are the US National Weather Service's.");
	} else if (status == 0) {
		p->error = g_strdup("Couldn't reach weathersnail. Check your "
			"connection.");
	} else {
		p->error = g_strdup_printf("weathersnail couldn't give a forecast "
			"(%d).", status);
	}
	ws_changed(p);
	req_free(r);
}

static void ask_forecast(struct ws_place *p) {
	struct req *r = g_new0(struct req, 1);
	r->id = g_strdup(p->id);
	r->units = units_name();
	char lat[G_ASCII_DTOSTR_BUF_SIZE], lon[G_ASCII_DTOSTR_BUF_SIZE];
	char *body = g_strdup_printf("{\"point\":[%s,%s],\"units\":\"%s\"}",
		g_ascii_formatd(lat, sizeof(lat), "%.4f", p->lat),
		g_ascii_formatd(lon, sizeof(lon), "%.4f", p->lon), r->units);
	p->loading = true;
	ws_http("POST", API "/api/forecast", body, NULL, got_forecast, r);
	g_free(body);
}

/* The conditions of several places at once: their ids, in order */
static void got_conditions(int status, const char *body, void *data) {
	char **ids = data;
	struct json *list = status == 200 && body ? json_parse(body) : NULL;
	for (int i = 0; list && ids[i]; i++) {
		struct ws_place *p = lookup(ids[i]);
		struct json *j = json_at(list, i);
		struct ws_now *n = now_parse(j);
		if (p == NULL || n == NULL) {
			now_free(n);
			continue;
		}
		now_free(p->now);
		p->now = n;
		/* Kept per place, to be read alone */
		char *text = json_dump(j);
		char *name = now_cache_name(p);
		save_cache(name, text);
		g_free(name);
		g_free(text);
		ws_changed(p);
	}
	json_free(list);
	g_strfreev(ids);
}

static void ask_conditions(struct ws_place **places, int count) {
	if (count == 0) {
		return;
	}
	GString *body = g_string_new("{\"points\":[");
	char **ids = g_new0(char *, count + 1);
	for (int i = 0; i < count; i++) {
		char lat[G_ASCII_DTOSTR_BUF_SIZE], lon[G_ASCII_DTOSTR_BUF_SIZE];
		g_string_append_printf(body, "%s[%s,%s,%d]", i ? "," : "",
			g_ascii_formatd(lat, sizeof(lat), "%.4f", places[i]->lat),
			g_ascii_formatd(lon, sizeof(lon), "%.4f", places[i]->lon),
			RAIN_RADIUS_KM);
		ids[i] = g_strdup(places[i]->id);
	}
	g_string_append(body, "]}");
	ws_http("POST", API "/api/conditions", body->str, NULL, got_conditions, ids);
	g_string_free(body, TRUE);
}

void ws_refresh(struct ws_place *p) {
	if (!p->loading) {
		ask_forecast(p);
	}
	ask_conditions(&p, 1);
	refresh_alerts(false);
}

void ws_refresh_all(void) {
	GPtrArray *all = g_ptr_array_new();
	for (guint i = 0; i < ws_places->len; i++) {
		g_ptr_array_add(all, ws_places->pdata[i]);
	}
	if (ws_preview && !ws_place_find(ws_preview->id)) {
		g_ptr_array_add(all, ws_preview);
	}
	for (guint i = 0; i < all->len; i++) {
		struct ws_place *p = all->pdata[i];
		if (!p->loading) {
			ask_forecast(p);
		}
	}
	for (guint i = 0; i < all->len; i += CONDITIONS_BATCH) {
		int n = MIN(CONDITIONS_BATCH, (int)(all->len - i));
		ask_conditions((struct ws_place **)all->pdata + i, n);
	}
	g_ptr_array_unref(all);
	refresh_alerts(true);
}

/* An alert's words */

struct text_req {
	ws_text_fn fn;
	void *data;
};

static void got_text(int status, const char *body, void *data) {
	struct text_req *t = data;
	struct json *j = status == 200 && body ? json_parse(body) : NULL;
	if (j) {
		t->fn(json_str(json_get(j, "description"), NULL),
			json_str(json_get(j, "instruction"), NULL), t->data);
	} else {
		t->fn(NULL, NULL, t->data);
	}
	json_free(j);
	g_free(t);
}

void ws_alert_text(const char *id, ws_text_fn fn, void *data) {
	struct text_req *t = g_new0(struct text_req, 1);
	t->fn = fn;
	t->data = data;
	char *esc = g_uri_escape_string(id, NULL, FALSE);
	char *url = g_strconcat(API "/api/alerts/text?id=", esc, NULL);
	ws_http("GET", url, NULL, NULL, got_text, t);
	g_free(url);
	g_free(esc);
}

/* Finding places */

struct find_req {
	ws_found_fn fn;
	void *data;
};

static void found_free(gpointer data) {
	struct ws_found *f = data;
	g_free(f->label);
	g_free(f->name);
	g_free(f->detail);
	g_free(f);
}

static void got_places(int status, const char *body, void *data) {
	struct find_req *r = data;
	struct json *list = status == 200 && body ? json_parse(body) : NULL;
	if (list == NULL || list->type != JSON_ARRAY) {
		json_free(list);
		r->fn(NULL, r->data);
		g_free(r);
		return;
	}
	GPtrArray *found = g_ptr_array_new_with_free_func(found_free);
	for (int i = 0; i < json_length(list); i++) {
		struct json *j = json_at(list, i);
		const char *kind = json_str(json_get(j, "kind"), "");
		const char *name = json_str(json_get(j, "name"), NULL);
		const char *region = json_str(json_get(j, "region"), NULL);
		const char *code = json_str(json_get(j, "code"), NULL);
		double lat = json_num(json_get(j, "lat"), NAN);
		double lon = json_num(json_get(j, "lon"), NAN);
		/* A state is too big to have weather, a radar isn't a place */
		if (name == NULL || isnan(lat) || isnan(lon) ||
				strcmp(kind, "radar") == 0 || json_get(j, "west") ||
				json_get(j, "bbox") || strcmp(kind, "state") == 0 ||
				strcmp(kind, "province") == 0) {
			continue;
		}
		struct ws_found *f = g_new0(struct ws_found, 1);
		f->lat = lat;
		f->lon = lon;
		char *town = region && region[0] ? g_strdup_printf("%s, %s", name,
			region) : g_strdup(name);
		if (strcmp(kind, "zip") == 0) {
			f->name = g_strdup(town);
			f->label = g_strdup_printf("%s %s", town, code ? code : "");
			f->detail = g_strdup("ZIP code");
		} else if (strcmp(kind, "airport") == 0) {
			f->name = g_strdup(name);
			f->label = code ? g_strdup_printf("%s (%s)", name, code) :
				g_strdup(name);
			f->detail = g_strdup("Airport");
		} else {
			f->name = g_strdup(town);
			f->label = g_strdup(town);
			f->detail = g_strdup(strcmp(kind, "city") == 0 ? "Town" : kind);
		}
		g_free(town);
		/* The same name twice (a city and its first ZIP code): once */
		bool dup = false;
		for (guint k = 0; k < found->len && !dup; k++) {
			dup = strcmp(((struct ws_found *)found->pdata[k])->label,
				f->label) == 0;
		}
		if (dup) {
			found_free(f);
		} else {
			g_ptr_array_add(found, f);
		}
	}
	json_free(list);
	r->fn(found, r->data);
	g_ptr_array_unref(found);
	g_free(r);
}

void ws_find_places(const char *query, ws_found_fn fn, void *data) {
	struct find_req *r = g_new0(struct find_req, 1);
	r->fn = fn;
	r->data = data;
	char *esc = g_uri_escape_string(query, NULL, FALSE);
	char *url = g_strconcat(API "/api/places?limit=8&q=", esc, NULL);
	ws_http("GET", url, NULL, NULL, got_places, r);
	g_free(url);
	g_free(esc);
}
