/*
 * What is kept: the places and the settings in
 * ~/.config/cont8nuum/weather.ini, and what the API answered in the cache
 * (~/.cache/cont8nuum/weather), so the weather shows before the network
 * answers.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stealth.h"
#include "weather.h"

/* Places closer than this are the same place (about 1 km) */
#define SAME_PLACE 0.01

struct ws_settings ws_settings = { .units = WS_FAHRENHEIT };
GPtrArray *ws_places;
static GPtrArray *local_places; // weather.ini's; ws_places unless synced

static char *config_path(void) {
	return g_build_filename(g_get_user_config_dir(), "cont8nuum", "weather.ini",
		NULL);
}

bool ws_id_ok(const char *id) {
	size_t n = id ? strlen(id) : 0;
	return n > 0 && n <= 64 && id[0] != '.' &&
		strspn(id, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
			"0123456789._-") == n;
}

/* Never outside the cache: a name with a folder in it is not one of ours */
char *ws_cache_path(const char *name) {
	if (strchr(name, '/') || strcmp(name, "..") == 0) {
		name = "refused";
	}
	return g_build_filename(g_get_user_cache_dir(), "cont8nuum", "weather", name,
		NULL);
}

struct ws_place *ws_place_new(const char *id, const char *name, double lat,
		double lon) {
	struct ws_place *p = g_new0(struct ws_place, 1);
	p->id = g_strdup(id);
	p->name = g_strdup(name);
	p->lat = lat;
	p->lon = lon;
	return p;
}

const char *ws_place_label(const struct ws_place *p) {
	return c8_stealth_alias(C8_STEALTH_PLACE, p->name);
}

void ws_place_free(gpointer data) {
	struct ws_place *p = data;
	if (p == NULL) {
		return;
	}
	ws_forget(p);
	g_free(p->id);
	g_free(p->name);
	g_free(p->error);
	g_free(p);
}

static struct ws_place *find_in(GPtrArray *list, const char *id) {
	for (guint i = 0; id && list && i < list->len; i++) {
		struct ws_place *p = list->pdata[i];
		if (strcmp(p->id, id) == 0) {
			return p;
		}
	}
	return NULL;
}

struct ws_place *ws_place_find(const char *id) {
	return find_in(ws_places, id);
}

struct ws_place *ws_place_near(GPtrArray *list, double lat, double lon) {
	for (guint i = 0; list && i < list->len; i++) {
		struct ws_place *p = list->pdata[i];
		if (fabs(p->lat - lat) < SAME_PLACE && fabs(p->lon - lon) < SAME_PLACE) {
			return p;
		}
	}
	return NULL;
}

struct ws_place *ws_home(void) {
	struct ws_place *p = ws_place_find(ws_settings.home);
	if (p == NULL && ws_places->len) {
		p = ws_places->pdata[0];
	}
	return p;
}

GPtrArray *ws_local_places(void) {
	return local_places;
}

void ws_use_places(GPtrArray *places) {
	ws_places = places ? places : local_places;
}

/* Our ids: from where it is, so the same place gets the same one */
static char *make_id(double lat, double lon) {
	char *where = g_strdup_printf("%.4f,%.4f", lat, lon);
	char *sum = g_compute_checksum_for_string(G_CHECKSUM_SHA1, where, -1);
	char *id = g_strdup_printf("c8-%.10s", sum);
	g_free(sum);
	g_free(where);
	return id;
}

void ws_load(void) {
	local_places = g_ptr_array_new_with_free_func(ws_place_free);
	ws_places = local_places;
	GKeyFile *kf = g_key_file_new();
	char *path = config_path();
	bool loaded = g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL);
	g_free(path);
	if (!loaded) {
		/* The API is the NWS's, so the US's units unless told */
		g_key_file_free(kf);
		return;
	}
	char *units = g_key_file_get_string(kf, "weather", "units", NULL);
	if (units) {
		ws_settings.units = strcmp(units, "c") == 0 ? WS_CELSIUS : WS_FAHRENHEIT;
	}
	g_free(units);
	ws_settings.home = g_key_file_get_string(kf, "weather", "home", NULL);
	char **order = g_key_file_get_string_list(kf, "weather", "places", NULL,
		NULL);
	for (char **o = order; o && *o; o++) {
		char *group = g_strconcat("place ", *o, NULL);
		char *name = g_key_file_get_string(kf, group, "name", NULL);
		GError *e1 = NULL, *e2 = NULL;
		double lat = g_key_file_get_double(kf, group, "lat", &e1);
		double lon = g_key_file_get_double(kf, group, "lon", &e2);
		if (name && !e1 && !e2 && !find_in(local_places, *o)) {
			g_ptr_array_add(local_places, ws_place_new(*o, name, lat, lon));
		}
		g_clear_error(&e1);
		g_clear_error(&e2);
		g_free(name);
		g_free(group);
	}
	g_strfreev(order);
	g_key_file_free(kf);
}

void ws_save(void) {
	GKeyFile *kf = g_key_file_new();
	g_key_file_set_comment(kf, NULL, NULL, " Weather's places and settings; "
		"the app writes this file", NULL);
	g_key_file_set_string(kf, "weather", "units",
		ws_settings.units == WS_CELSIUS ? "c" : "f");
	if (ws_settings.home) {
		g_key_file_set_string(kf, "weather", "home", ws_settings.home);
	}
	GPtrArray *ids = g_ptr_array_new();
	for (guint i = 0; i < local_places->len; i++) {
		struct ws_place *p = local_places->pdata[i];
		g_ptr_array_add(ids, p->id);
		char *group = g_strconcat("place ", p->id, NULL);
		g_key_file_set_string(kf, group, "name", p->name);
		char num[G_ASCII_DTOSTR_BUF_SIZE];
		g_key_file_set_value(kf, group, "lat",
			g_ascii_formatd(num, sizeof(num), "%.5f", p->lat));
		g_key_file_set_value(kf, group, "lon",
			g_ascii_formatd(num, sizeof(num), "%.5f", p->lon));
		g_free(group);
	}
	g_key_file_set_string_list(kf, "weather", "places",
		(const char *const *)ids->pdata, ids->len);
	g_ptr_array_unref(ids);
	char *path = config_path();
	char *dir = g_path_get_dirname(path);
	g_mkdir_with_parents(dir, 0700);
	g_key_file_save_to_file(kf, path, NULL);
	g_free(dir);
	g_free(path);
	g_key_file_free(kf);
}

struct ws_place *ws_add_place(const char *name, double lat, double lon) {
	if (ws_place_near(ws_places, lat, lon)) {
		return NULL;
	}
	char *id = make_id(lat, lon);
	struct ws_place *p = ws_place_new(id, name, lat, lon);
	g_free(id);
	if (ws_synced) {
		/* The account's list gets it, as a marker: account.c adds it to
		 * ws_places now, and keeps it there once the server has it */
		ws_account_add(p);
		return p;
	}
	g_ptr_array_add(local_places, p);
	if (ws_places->len == 1 && ws_settings.home == NULL) {
		ws_settings.home = g_strdup(p->id);
	}
	ws_save();
	return p;
}

void ws_remove_place(struct ws_place *place) {
	if (g_strcmp0(ws_settings.home, place->id) == 0) {
		g_clear_pointer(&ws_settings.home, g_free);
	}
	if (place->remote) {
		ws_account_remove(place);
		ws_save();
		return;
	}
	g_ptr_array_remove(local_places, place);
	ws_save();
}

void ws_set_home(struct ws_place *place) {
	g_free(ws_settings.home);
	ws_settings.home = g_strdup(place->id);
	/* First in the list too, as Windows 8's Places had it */
	GPtrArray *list = ws_places;
	for (guint i = 1; i < list->len; i++) {
		if (list->pdata[i] == place) {
			g_ptr_array_steal_index(list, i);
			g_ptr_array_insert(list, 0, place);
			break;
		}
	}
	ws_save();
}
