/*
 * The live tile: how many of our devices are online, the first few by
 * name, and the exit node in use; or why there is nothing to show, over
 * org.cont8nuum.Tiles1. The app sends it under its own id and the
 * widget's; c8-tailscale-tile under the widget's while the app isn't open.
 */
#include <gio/gio.h>
#include <string.h>
#include "tiles.h"
#include "tailscale.h"

#define NAMES 5
/* Windows Phone's status colours, as the other widgets use them */
#define COLOR_WARN "#fa6800"
#define COLOR_MUTED "#647687"

/* A tile is sent again only when it changed, or after this long (the
 * status is read every few seconds, mostly the same; the resend is for a
 * tile pinned since) */
#define RESEND_S 300

struct sent {
	GVariant *content;
	char *badge;
	gint64 at; // seconds
};

static GHashTable *sent; // tile id -> struct sent

static void sent_free(gpointer data) {
	struct sent *s = data;
	g_variant_unref(s->content);
	g_free(s->badge);
	g_free(s);
}

void ts_tile_forget(void) {
	if (sent) {
		g_hash_table_remove_all(sent);
	}
}

/* A new shell (or the first): it may not have what we sent */
static void shell_appeared(GDBusConnection *c, const char *name,
		const char *owner, gpointer data) {
	ts_tile_forget();
}

static void call(const char *method, GVariant *params) {
	static bool watching;
	GDBusConnection *bus = c8_tiles_bus();
	if (bus && !watching) {
		watching = true;
		g_bus_watch_name_on_connection(bus, C8_TILES_NAME,
			G_BUS_NAME_WATCHER_FLAGS_NONE, shell_appeared, NULL, NULL, NULL);
	}
	c8_tiles_call(method, params);
}

static void add(GVariantBuilder *b, const char *key, const char *value) {
	if (value && value[0]) {
		g_variant_builder_add(b, "{ss}", key, value);
	}
}

void ts_tile_update(const char *tile) {
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
	add(&b, "label", "Tailscale");
	switch (ts.state) {
	case TS_NOT_INSTALLED:
		add(&b, "heading", "Not installed");
		add(&b, "color", COLOR_MUTED);
		break;
	case TS_NO_DAEMON:
		add(&b, "heading", "Not running");
		add(&b, "text1", "tailscaled isn't answering");
		add(&b, "color", COLOR_MUTED);
		break;
	case TS_NEEDS_LOGIN:
		add(&b, "heading", "Not logged in");
		add(&b, "text1", "Open to log in");
		add(&b, "color", COLOR_WARN);
		break;
	case TS_NEEDS_MACHINE_AUTH:
		add(&b, "heading", "Waiting for approval");
		add(&b, "text1", "An admin has to approve this device");
		add(&b, "color", COLOR_WARN);
		break;
	case TS_STOPPED:
		add(&b, "heading", "Disconnected");
		add(&b, "text1", "Open to connect");
		add(&b, "color", COLOR_MUTED);
		break;
	case TS_STARTING:
		add(&b, "heading", "Connecting…");
		break;
	case TS_RUNNING: {
		int online, total;
		ts_count(&online, &total);
		char block[16], line[64];
		g_snprintf(block, sizeof(block), "%d", online);
		g_snprintf(line, sizeof(line), "of %d device%s online", total,
			total == 1 ? "" : "s");
		add(&b, "template", "block");
		add(&b, "block", block);
		add(&b, "text1", line);
		/* Online devices first, then when the others were last seen */
		int n = 2;
		for (guint i = 0; i < ts.peers->len && n < 2 + NAMES; i++) {
			struct ts_peer *p = ts.peers->pdata[i];
			if (p->mullvad) {
				continue;
			}
			char key[8];
			g_snprintf(key, sizeof(key), "text%d", n++);
			char *age = ts_age(p->last_seen);
			char *text = g_strdup_printf("%s\t%s", ts_shown_name(p), p->online ? "online" :
				age[0] ? age : "offline");
			add(&b, key, text);
			g_free(text);
			g_free(age);
		}
		struct ts_peer *exit = ts_exit_node();
		if (exit) {
			char *text = g_strdup_printf("Exit node\t%s", exit->city ? exit->city :
				ts_shown_name(exit));
			add(&b, "large.text7", text);
			g_free(text);
		}
		break;
	}
	}
	GVariant *content = g_variant_ref_sink(g_variant_new("(ssa{ss})", tile,
		"", &b));
	/* An exit node in use shows in the corner at every size */
	const char *badge = ts.state == TS_RUNNING && ts_exit_node() ? "⇄" : "";
	gint64 now = g_get_monotonic_time() / G_USEC_PER_SEC;
	if (sent == NULL) {
		sent = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
			sent_free);
	}
	struct sent *last = g_hash_table_lookup(sent, tile);
	if (last && now - last->at < RESEND_S && strcmp(last->badge, badge) == 0 &&
			g_variant_equal(last->content, content)) {
		g_variant_unref(content);
		return;
	}
	call("Update", content);
	call("SetBadge", g_variant_new("(ss)", tile, badge));
	last = g_new0(struct sent, 1);
	last->content = content;
	last->badge = g_strdup(badge);
	last->at = now;
	g_hash_table_replace(sent, g_strdup(tile), last);
}
