/*
 * The weathersnail account (snail.zone, from PC settings' Online
 * accounts): while there is one with Weather turned on, the favourites
 * are the markers saved on it, so they're the same here, on other PCs and
 * on weathersnail.com's map. Adding a place adds a marker, removing one
 * deletes it. Without an account, weather.ini's places are used.
 *
 * The token comes from c8-accounts (org.cont8nuum.Accounts1), which
 * refreshes it; a 401 hands the rejected one back for a new one, once.
 * The markers are kept in the cache so the places show before the
 * network answers. The first time an account is used, our places that it
 * doesn't have are added to it, once.
 */
#include <gio/gio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "json.h"
#include "weather.h"

#define SERVICE "weathersnail"
#define ACCOUNTS "org.cont8nuum.Accounts"
#define ACCOUNTS_PATH "/org/cont8nuum/Accounts"
#define ACCOUNTS_IFACE "org.cont8nuum.Accounts1"
#define MARKER_COLOR "#1e6fb8" // Weather's blue

bool ws_synced;

static struct {
	GDBusConnection *bus;
	char *account, *token, *api, *who;
	bool attached, asking, syncing;
	GPtrArray *waiting; // struct call, until there's a token
	GPtrArray *places; // struct ws_place, the markers, while synced
	ws_remote_fn fn;
	void *data;
	char *error;
	bool told_sign_in;
	bool may_import;
} ac;

static char *state_path(void) {
	return g_build_filename(g_get_user_data_dir(), "cont8nuum", "weather",
		"account.ini", NULL);
}

static GKeyFile *state_load(void) {
	GKeyFile *kf = g_key_file_new();
	char *path = state_path();
	g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL);
	g_free(path);
	return kf;
}

static void state_save(GKeyFile *kf) {
	char *path = state_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);
}

static void tell(const char *error, bool loud) {
	if (ac.fn) {
		ac.fn(error, loud, ac.data);
	}
}

static void set_error(const char *error) {
	g_free(ac.error);
	ac.error = g_strdup(error);
}

const char *ws_account_error(void) {
	return ac.error;
}

const char *ws_account_name(void) {
	return ac.who;
}

/* Calls to the account API */

typedef void (*api_fn)(int status, const char *body, void *data);

struct call {
	char *method, *path, *body;
	api_fn fn;
	void *data;
	bool retried;
};

static void call_free(struct call *c) {
	g_free(c->method);
	g_free(c->path);
	g_free(c->body);
	g_free(c);
}

static void get_token(const char *rejected);
static void call_run(struct call *c);

static void call_done(int status, const char *body, void *data) {
	struct call *c = data;
	if (status == 401 && !c->retried && ac.token) {
		/* Ran out early, or was revoked: a new one, once */
		c->retried = true;
		char *rejected = g_steal_pointer(&ac.token);
		g_ptr_array_add(ac.waiting, c);
		get_token(rejected);
		g_free(rejected);
		return;
	}
	if (status == 403 && body && strstr(body, "insufficient_scope")) {
		/* A token from before Weather was asked for: refreshing won't
		 * add it */
		bool loud = !ac.told_sign_in;
		ac.told_sign_in = true;
		set_error("Sign in to your snail.zone account again in PC settings, "
			"under Online accounts, to let Weather see your places.");
		tell(ac.error, loud);
	}
	c->fn(status, body, c->data);
	call_free(c);
}

static void call_run(struct call *c) {
	char *url = g_strconcat(ac.api, c->path, NULL);
	ws_http(c->method, url, c->body, ac.token, call_done, c);
	g_free(url);
}

static void api(const char *method, const char *path, const char *body,
		api_fn fn, void *data) {
	struct call *c = g_new0(struct call, 1);
	c->method = g_strdup(method);
	c->path = g_strdup(path);
	c->body = g_strdup(body);
	c->fn = fn;
	c->data = data;
	if (ac.token) {
		call_run(c);
		return;
	}
	g_ptr_array_add(ac.waiting, c);
	get_token(NULL);
}

static void fail_waiting(void) {
	GPtrArray *list = ac.waiting;
	ac.waiting = g_ptr_array_new();
	for (guint i = 0; i < list->len; i++) {
		struct call *c = list->pdata[i];
		c->fn(0, NULL, c->data);
		call_free(c);
	}
	g_ptr_array_unref(list);
}

/* Markers as places */

static char *markers_path(void) {
	return ws_cache_path("markers.json");
}

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

static char *signature(GPtrArray *list) {
	GString *s = g_string_new(NULL);
	for (guint i = 0; list && i < list->len; i++) {
		struct ws_place *p = list->pdata[i];
		g_string_append_printf(s, "%s\n%s\n%.4f %.4f\n", p->id, p->name, p->lat,
			p->lon);
	}
	return g_string_free(s, FALSE);
}

/* The new list, keeping the places (and their weather) still in it; true
 * if anything shown changed */
static bool take_markers(struct json *list) {
	GPtrArray *old = ac.places;
	GPtrArray *now = g_ptr_array_new_with_free_func(ws_place_free);
	char *before = old ? signature(old) : NULL;
	for (int i = 0; i < json_length(list); i++) {
		struct json *m = json_at(list, i);
		const char *id = json_str(json_get(m, "id"), NULL);
		const char *name = json_str(json_get(m, "name"), NULL);
		double lat = json_num(json_get(m, "lat"), NAN);
		double lon = json_num(json_get(m, "lon"), NAN);
		if (!ws_id_ok(id) || name == NULL || isnan(lat) || isnan(lon)) {
			continue;
		}
		struct ws_place *p = steal_place(old, id);
		if (p == NULL) {
			p = ws_place_new(id, name, lat, lon);
			p->remote = true;
			ws_load_cached(p);
		}
		g_free(p->name);
		p->name = g_strdup(name);
		p->lat = lat;
		p->lon = lon;
		g_ptr_array_add(now, p);
	}
	/* The default first, as ws_set_home keeps it */
	for (guint i = 1; i < now->len; i++) {
		struct ws_place *p = now->pdata[i];
		if (g_strcmp0(p->id, ws_settings.home) == 0) {
			g_ptr_array_steal_index(now, i);
			g_ptr_array_insert(now, 0, p);
			break;
		}
	}
	ac.places = now;
	char *after = signature(now);
	bool changed = before == NULL || strcmp(before, after) != 0;
	g_free(before);
	g_free(after);
	if (ws_synced) {
		ws_use_places(now);
	}
	if (old) {
		g_ptr_array_unref(old); // what is left in it went
	}
	return changed;
}

static bool load_cached_markers(void) {
	char *path = markers_path(), *text = NULL;
	bool ok = false;
	if (g_file_get_contents(path, &text, NULL, NULL)) {
		struct json *list = json_parse(text);
		if (list && list->type == JSON_ARRAY) {
			take_markers(list);
			ok = true;
		}
		json_free(list);
		g_free(text);
	}
	g_free(path);
	return ok;
}

/* Our own list in the cache's form, after a change made here */
static void save_markers(void) {
	GString *s = g_string_new("[");
	for (guint i = 0; ac.places && i < ac.places->len; i++) {
		struct ws_place *p = ac.places->pdata[i];
		char *id = ws_json_escape(p->id), *name = ws_json_escape(p->name);
		char lat[G_ASCII_DTOSTR_BUF_SIZE], lon[G_ASCII_DTOSTR_BUF_SIZE];
		g_string_append_printf(s, "%s{\"id\":\"%s\",\"name\":\"%s\",\"lat\":%s,"
			"\"lon\":%s}", i ? "," : "", id, name,
			g_ascii_formatd(lat, sizeof(lat), "%.5f", p->lat),
			g_ascii_formatd(lon, sizeof(lon), "%.5f", p->lon));
		g_free(id);
		g_free(name);
	}
	g_string_append(s, "]");
	char *path = markers_path();
	char *dir = g_path_get_dirname(path);
	g_mkdir_with_parents(dir, 0700);
	g_file_set_contents(path, s->str, -1, NULL);
	g_free(dir);
	g_free(path);
	g_string_free(s, TRUE);
}

static void import_local(struct json *markers);

static void got_markers(int status, const char *body, void *data) {
	ac.syncing = false;
	if (!ac.attached) {
		return;
	}
	struct json *list = status == 200 && body ? json_parse(body) : NULL;
	if (list == NULL || list->type != JSON_ARRAY) {
		json_free(list);
		if (status == 403) {
			return; // said in call_done
		}
		char *e = status ? g_strdup_printf("weathersnail said %d", status) :
			g_strdup("Couldn't reach weathersnail");
		set_error(e);
		tell(e, false);
		g_free(e);
		return;
	}
	set_error(NULL);
	char *path = markers_path();
	char *dir = g_path_get_dirname(path);
	g_mkdir_with_parents(dir, 0700);
	g_file_set_contents(path, body, -1, NULL);
	g_free(dir);
	g_free(path);
	bool first = !ws_synced;
	ws_synced = true;
	bool changed = take_markers(list);
	ws_use_places(ac.places);
	import_local(list);
	if (changed || first) {
		tell(NULL, false);
	}
	json_free(list);
}

void ws_account_sync(void) {
	if (!ac.attached || ac.syncing) {
		return;
	}
	ac.syncing = true;
	api("GET", "/api/account/markers", NULL, got_markers, NULL);
}

static void got_me(int status, const char *body, void *data) {
	struct json *j = status == 200 && body ? json_parse(body) : NULL;
	const char *nick = json_str(json_get(j, "nickname"), NULL);
	const char *name = json_str(json_get(j, "name"), NULL);
	g_free(ac.who);
	ac.who = g_strdup(nick && nick[0] ? nick : name);
	json_free(j);
}

/* Adding and removing */

static void put_done(int status, const char *body, void *data) {
	char *id = data;
	if (status < 200 || status >= 300) {
		/* Not there after all */
		struct ws_place *p = steal_place(ac.places, id);
		if (p) {
			ws_place_free(p);
			save_markers();
		}
		char *e = status ? g_strdup_printf("weathersnail couldn't save the "
			"place (%d).", status) : g_strdup("Couldn't reach weathersnail "
			"to save the place.");
		tell(e, true);
		g_free(e);
		tell(NULL, false);
	}
	g_free(id);
}

static void put_marker(struct ws_place *p, api_fn fn, void *data) {
	char *id = ws_json_escape(p->id);
	char *name = ws_json_escape(p->name);
	GDateTime *now = g_date_time_new_now_utc();
	char *created = g_date_time_format_iso8601(now);
	g_date_time_unref(now);
	char lat[G_ASCII_DTOSTR_BUF_SIZE], lon[G_ASCII_DTOSTR_BUF_SIZE];
	char *body = g_strdup_printf("{\"id\":\"%s\",\"name\":\"%s\",\"lat\":%s,"
		"\"lon\":%s,\"color\":\"" MARKER_COLOR "\",\"style\":\"pin\","
		"\"note\":\"\",\"created\":\"%s\",\"notify\":null}", id, name,
		g_ascii_formatd(lat, sizeof(lat), "%.5f", p->lat),
		g_ascii_formatd(lon, sizeof(lon), "%.5f", p->lon), created);
	char *esc = g_uri_escape_string(p->id, NULL, FALSE);
	char *path = g_strconcat("/api/account/markers/", esc, NULL);
	api("PUT", path, body, fn, data);
	g_free(path);
	g_free(esc);
	g_free(body);
	g_free(created);
	g_free(name);
	g_free(id);
}

void ws_account_add(struct ws_place *p) {
	p->remote = true;
	/* Shown at once; taken back if the server says no */
	g_ptr_array_add(ac.places, p);
	ws_use_places(ac.places);
	save_markers();
	put_marker(p, put_done, g_strdup(p->id));
}

static void delete_done(int status, const char *body, void *data) {
	if ((status < 200 || status >= 300) && status != 404) {
		tell(status ? "weathersnail couldn't remove the place." :
			"Couldn't reach weathersnail to remove the place.", true);
		/* What it really has */
		ws_account_sync();
	}
}

void ws_account_remove(struct ws_place *p) {
	char *esc = g_uri_escape_string(p->id, NULL, FALSE);
	char *path = g_strconcat("/api/account/markers/", esc, NULL);
	api("DELETE", path, NULL, delete_done, NULL);
	g_free(path);
	g_free(esc);
	g_ptr_array_remove(ac.places, p); // frees it
	save_markers();
}

/* Our places onto an account used for the first time, once */

static void imported_one(int status, const char *body, void *data) {
	if (GPOINTER_TO_INT(data)) {
		ac.syncing = false;
		ws_account_sync(); // the last one: show them all
	}
}

static void import_local(struct json *markers) {
	if (!ac.may_import) {
		return;
	}
	GKeyFile *kf = state_load();
	char **done = g_key_file_get_string_list(kf, "account", "imported", NULL,
		NULL);
	if (done && g_strv_contains((const char *const *)done, ac.account)) {
		g_strfreev(done);
		g_key_file_free(kf);
		return;
	}
	GPtrArray *local = ws_local_places();
	GPtrArray *todo = g_ptr_array_new();
	for (guint i = 0; i < local->len; i++) {
		struct ws_place *p = local->pdata[i];
		if (!ws_place_near(ac.places, p->lat, p->lon)) {
			g_ptr_array_add(todo, p);
		}
	}
	for (guint i = 0; i < todo->len; i++) {
		bool last = i + 1 == todo->len;
		if (last) {
			ac.syncing = true; // the sync after the last shows them
		}
		put_marker(todo->pdata[i], imported_one, GINT_TO_POINTER(last));
	}
	g_ptr_array_unref(todo);
	/* Remembered now: one that failed isn't tried again and again */
	GPtrArray *list = g_ptr_array_new();
	for (char **d = done; d && *d; d++) {
		g_ptr_array_add(list, *d);
	}
	g_ptr_array_add(list, ac.account);
	g_key_file_set_string_list(kf, "account", "imported",
		(const char *const *)list->pdata, list->len);
	g_ptr_array_unref(list);
	state_save(kf);
	g_strfreev(done);
	g_key_file_free(kf);
}

/* Becoming synced, or not */

static void detach(void) {
	bool was = ws_synced;
	ws_synced = false;
	ac.attached = false;
	g_clear_pointer(&ac.account, g_free);
	g_clear_pointer(&ac.token, g_free);
	g_clear_pointer(&ac.api, g_free);
	g_clear_pointer(&ac.who, g_free);
	set_error(NULL);
	GKeyFile *kf = state_load();
	g_key_file_remove_key(kf, "account", "account", NULL);
	state_save(kf);
	g_key_file_free(kf);
	char *path = markers_path();
	g_unlink(path);
	g_free(path);
	if (was) {
		ws_use_places(NULL);
		tell(NULL, false); // the app lets go of the account's places here
	}
	g_clear_pointer(&ac.places, g_ptr_array_unref);
}

static void attach(const char *account) {
	bool other = ac.account == NULL || strcmp(ac.account, account) != 0;
	if (ac.attached && !other) {
		return;
	}
	if (other && ac.places) {
		/* Another account's places aren't this one's */
		if (ws_synced) {
			ws_synced = false;
			ws_use_places(NULL);
			tell(NULL, false);
		}
		g_clear_pointer(&ac.places, g_ptr_array_unref);
		char *path = markers_path();
		g_unlink(path);
		g_free(path);
	}
	if (ac.places == NULL) {
		ac.places = g_ptr_array_new_with_free_func(ws_place_free);
	}
	g_free(ac.account);
	ac.account = g_strdup(account);
	GKeyFile *kf = state_load();
	g_key_file_set_string(kf, "account", "account", account);
	state_save(kf);
	g_key_file_free(kf);
	ac.attached = true;
	ws_account_sync(); // ws_synced once they come
	api("GET", "/api/account/me", NULL, got_me, NULL);
}

static void got_token(GObject *source, GAsyncResult *res, gpointer data) {
	ac.asking = false;
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&error);
	if (r == NULL) {
		char *remote = g_dbus_error_get_remote_error(error);
		g_dbus_error_strip_remote_error(error);
		if (remote && (g_str_has_suffix(remote, ".NoAccount") ||
				strcmp(remote, "org.freedesktop.DBus.Error.ServiceUnknown") == 0)) {
			fail_waiting();
			detach();
		} else {
			/* Sign in again, offline, wallet shut: keep what we have */
			bool again = remote && g_str_has_suffix(remote, ".SignInNeeded");
			bool loud = again && !ac.told_sign_in;
			ac.told_sign_in |= again;
			set_error(again ? "Sign in to your snail.zone account again in PC "
				"settings, under Online accounts." : error->message);
			fail_waiting();
			tell(ac.error, loud);
		}
		g_free(remote);
		g_error_free(error);
		return;
	}
	const char *account, *token, *api_url;
	g_variant_get(r, "(&s&s&s)", &account, &token, &api_url);
	if (!g_str_has_prefix(api_url, "https://") &&
			!(ws_allow_http() && g_str_has_prefix(api_url, "http://"))) {
		g_variant_unref(r);
		set_error("The weathersnail account has no https address");
		fail_waiting();
		tell(ac.error, false);
		return;
	}
	ac.told_sign_in = false;
	g_free(ac.token);
	ac.token = g_strdup(token);
	g_free(ac.api);
	ac.api = g_strdup(api_url);
	char *acct = g_strdup(account);
	g_variant_unref(r);
	attach(acct);
	g_free(acct);
	GPtrArray *list = ac.waiting;
	ac.waiting = g_ptr_array_new();
	for (guint i = 0; i < list->len; i++) {
		call_run(list->pdata[i]);
	}
	g_ptr_array_unref(list);
}

static void get_token(const char *rejected) {
	if (ac.asking) {
		return;
	}
	if (ac.bus == NULL) {
		fail_waiting();
		return;
	}
	ac.asking = true;
	g_dbus_connection_call(ac.bus, ACCOUNTS, ACCOUNTS_PATH, ACCOUNTS_IFACE,
		"GetAccessToken", g_variant_new("(ss)", SERVICE, rejected ? rejected : ""),
		G_VARIANT_TYPE("(sss)"), G_DBUS_CALL_FLAGS_NONE, 60000, NULL, got_token,
		NULL);
}

/* PC settings changed the accounts: is there one for us still? */
static void accounts_changed(GDBusConnection *c, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data) {
	g_clear_pointer(&ac.token, g_free);
	get_token(NULL);
}

void ws_account_init(ws_remote_fn fn, void *data, bool may_import) {
	ac.may_import = may_import;
	ac.fn = fn;
	ac.data = data;
	ac.waiting = g_ptr_array_new();
	ac.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
	if (ac.bus) {
		g_dbus_connection_signal_subscribe(ac.bus, NULL, ACCOUNTS_IFACE,
			"Changed", ACCOUNTS_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
			accounts_changed, NULL, NULL);
	}
	/* Synced last time: those places at once, from the cache */
	GKeyFile *kf = state_load();
	char *account = g_key_file_get_string(kf, "account", "account", NULL);
	g_key_file_free(kf);
	if (account && load_cached_markers()) {
		ac.account = account;
		ac.attached = false; // attach again when the token comes
		ws_synced = true;
		ws_use_places(ac.places);
	} else {
		g_free(account);
	}
	get_token(NULL);
}
