/*
 * Network, from NetworkManager: each connection with its addresses,
 * Airplane mode and the radios, and the Wi-Fi networks it remembers
 * (forgetting one deletes it). Connecting is the Networks flyout's job.
 * NetworkManager is read on a worker thread, again a moment after it
 * says something changed.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <gio/gio.h>
#include "settings.h"
#include "rfkill.h"

#define NM "org.freedesktop.NetworkManager"
#define NM_PATH "/org/freedesktop/NetworkManager"
#define NM_SETTINGS "/org/freedesktop/NetworkManager/Settings"
#define NM_DEVICE NM ".Device"
#define SETTLE_MS 400

enum { TYPE_ETHERNET = 1, TYPE_WIFI = 2, TYPE_MODEM = 8 };
enum {
	STATE_UNMANAGED = 10,
	STATE_UNAVAILABLE = 20,
	STATE_DISCONNECTED = 30,
	STATE_ACTIVATED = 100,
	STATE_DEACTIVATING = 110,
	STATE_FAILED = 120,
};

struct device {
	char *iface;
	unsigned type, state;
	char *conn; // the active connection's name
	char *ip4, *gateway, *dns, *ip6, *mac;
	unsigned speed; // Mb/s, 0 not known
	int strength; // Wi-Fi signal, -1 not Wi-Fi
};

struct saved {
	char *path, *name;
	guint64 used;
};

struct snapshot {
	GArray *devices; // struct device
	GArray *saved; // struct saved, Wi-Fi only, most recent first
	bool wifi_on, wwan_on, has_wifi, has_wwan, ok;
};

static struct {
	GDBusConnection *bus;
	guint sub, settle;
	bool reading, again;
	GHashTable *open; // iface: its details are shown
	struct c8ui_widget *page, *connections, *airplane, *switched, *wifi, *wwan;
	struct c8ui_widget *known;
	struct snapshot *now;
} nw;

/* Reading, on the worker thread */

static GVariant *get(const char *path, const char *iface, const char *name) {
	GVariant *r = g_dbus_connection_call_sync(nw.bus, NM, path,
		"org.freedesktop.DBus.Properties", "Get",
		g_variant_new("(ss)", iface, name), G_VARIANT_TYPE("(v)"),
		G_DBUS_CALL_FLAGS_NONE, 2000, NULL, NULL);
	if (r == NULL) {
		return NULL;
	}
	GVariant *v;
	g_variant_get(r, "(v)", &v);
	g_variant_unref(r);
	return v;
}

static char *get_string(const char *path, const char *iface, const char *name) {
	GVariant *v = get(path, iface, name);
	char *s = v && g_variant_is_of_type(v, G_VARIANT_TYPE_STRING) ?
		g_variant_dup_string(v, NULL) : NULL;
	if (v) {
		g_variant_unref(v);
	}
	if (s && s[0] == '\0') {
		g_clear_pointer(&s, g_free);
	}
	return s;
}

static guint32 get_u32(const char *path, const char *iface, const char *name) {
	GVariant *v = get(path, iface, name);
	guint32 n = 0;
	if (v && g_variant_is_of_type(v, G_VARIANT_TYPE_UINT32)) {
		n = g_variant_get_uint32(v);
	} else if (v && g_variant_is_of_type(v, G_VARIANT_TYPE_BYTE)) {
		n = g_variant_get_byte(v);
	}
	if (v) {
		g_variant_unref(v);
	}
	return n;
}

static bool get_bool(const char *path, const char *iface, const char *name) {
	GVariant *v = get(path, iface, name);
	bool b = v && g_variant_is_of_type(v, G_VARIANT_TYPE_BOOLEAN) &&
		g_variant_get_boolean(v);
	if (v) {
		g_variant_unref(v);
	}
	return b;
}

/* An object path property; NULL for none ("/") */
static char *get_path(const char *path, const char *iface, const char *name) {
	GVariant *v = get(path, iface, name);
	char *p = v && g_variant_is_of_type(v, G_VARIANT_TYPE_OBJECT_PATH) ?
		g_variant_dup_string(v, NULL) : NULL;
	if (v) {
		g_variant_unref(v);
	}
	if (p && strcmp(p, "/") == 0) {
		g_clear_pointer(&p, g_free);
	}
	return p;
}

/* "address" of each dict in an aa{sv}, with its prefix if asked */
static char *addresses(const char *path, const char *iface, const char *name,
		bool prefix) {
	GVariant *v = get(path, iface, name);
	if (v == NULL || !g_variant_is_of_type(v, G_VARIANT_TYPE("aa{sv}"))) {
		if (v) {
			g_variant_unref(v);
		}
		return NULL;
	}
	GString *out = g_string_new(NULL);
	GVariantIter iter;
	GVariant *dict;
	g_variant_iter_init(&iter, v);
	while ((dict = g_variant_iter_next_value(&iter))) {
		const char *addr;
		guint32 len;
		if (g_variant_lookup(dict, "address", "&s", &addr)) {
			if (out->len) {
				g_string_append(out, ", ");
			}
			g_string_append(out, addr);
			if (prefix && g_variant_lookup(dict, "prefix", "u", &len)) {
				g_string_append_printf(out, "/%u", len);
			}
		}
		g_variant_unref(dict);
	}
	g_variant_unref(v);
	return g_string_free(out, out->len == 0);
}

static void read_device(const char *path, struct snapshot *s) {
	unsigned type = get_u32(path, NM_DEVICE, "DeviceType");
	if (type != TYPE_ETHERNET && type != TYPE_WIFI && type != TYPE_MODEM) {
		return;
	}
	struct device d = { .type = type, .strength = -1 };
	d.state = get_u32(path, NM_DEVICE, "State");
	if (d.state == STATE_UNMANAGED) {
		return;
	}
	d.iface = get_string(path, NM_DEVICE, "Interface");
	d.mac = get_string(path, NM_DEVICE, "HwAddress");
	s->has_wifi |= type == TYPE_WIFI;
	s->has_wwan |= type == TYPE_MODEM;
	char *active = get_path(path, NM_DEVICE, "ActiveConnection");
	if (active) {
		d.conn = get_string(active, NM ".Connection.Active", "Id");
		g_free(active);
	}
	char *ip4 = get_path(path, NM_DEVICE, "Ip4Config");
	if (ip4 && d.state == STATE_ACTIVATED) {
		d.ip4 = addresses(ip4, NM ".IP4Config", "AddressData", true);
		d.gateway = get_string(ip4, NM ".IP4Config", "Gateway");
		d.dns = addresses(ip4, NM ".IP4Config", "NameserverData", false);
	}
	g_free(ip4);
	char *ip6 = get_path(path, NM_DEVICE, "Ip6Config");
	if (ip6 && d.state == STATE_ACTIVATED) {
		d.ip6 = addresses(ip6, NM ".IP6Config", "AddressData", true);
	}
	g_free(ip6);
	if (type == TYPE_ETHERNET) {
		d.speed = get_u32(path, NM_DEVICE ".Wired", "Speed");
	} else if (type == TYPE_WIFI && d.state == STATE_ACTIVATED) {
		d.speed = get_u32(path, NM_DEVICE ".Wireless", "Bitrate") / 1000;
		char *ap = get_path(path, NM_DEVICE ".Wireless", "ActiveAccessPoint");
		if (ap) {
			d.strength = get_u32(ap, NM ".AccessPoint", "Strength");
			g_free(ap);
		}
	}
	g_array_append_val(s->devices, d);
}

static void read_saved(struct snapshot *s) {
	GVariant *r = g_dbus_connection_call_sync(nw.bus, NM, NM_SETTINGS,
		NM ".Settings", "ListConnections", NULL, G_VARIANT_TYPE("(ao)"),
		G_DBUS_CALL_FLAGS_NONE, 2000, NULL, NULL);
	if (r == NULL) {
		return;
	}
	GVariantIter *iter;
	const char *path;
	g_variant_get(r, "(ao)", &iter);
	while (g_variant_iter_next(iter, "&o", &path)) {
		GVariant *c = g_dbus_connection_call_sync(nw.bus, NM, path,
			NM ".Settings.Connection", "GetSettings", NULL,
			G_VARIANT_TYPE("(a{sa{sv}})"), G_DBUS_CALL_FLAGS_NONE, 2000, NULL,
			NULL);
		if (c == NULL) {
			continue;
		}
		GVariant *all = g_variant_get_child_value(c, 0);
		GVariant *conn = g_variant_lookup_value(all, "connection",
			G_VARIANT_TYPE("a{sv}"));
		const char *type = NULL, *id = NULL;
		guint64 used = 0;
		if (conn) {
			g_variant_lookup(conn, "type", "&s", &type);
			g_variant_lookup(conn, "id", "&s", &id);
			g_variant_lookup(conn, "timestamp", "t", &used);
		}
		if (type && id && strcmp(type, "802-11-wireless") == 0) {
			struct saved v = { g_strdup(path), g_strdup(id), used };
			g_array_append_val(s->saved, v);
		}
		g_clear_pointer(&conn, g_variant_unref);
		g_variant_unref(all);
		g_variant_unref(c);
	}
	g_variant_iter_free(iter);
	g_variant_unref(r);
}

static int by_use(gconstpointer a, gconstpointer b) {
	const struct saved *x = a, *y = b;
	return x->used < y->used ? 1 : x->used > y->used ? -1 :
		g_utf8_collate(x->name, y->name);
}

static void snapshot_free(gpointer data) {
	struct snapshot *s = data;
	if (s == NULL) {
		return;
	}
	for (guint i = 0; i < s->devices->len; i++) {
		struct device *d = &g_array_index(s->devices, struct device, i);
		g_free(d->iface);
		g_free(d->conn);
		g_free(d->ip4);
		g_free(d->gateway);
		g_free(d->dns);
		g_free(d->ip6);
		g_free(d->mac);
	}
	for (guint i = 0; i < s->saved->len; i++) {
		struct saved *v = &g_array_index(s->saved, struct saved, i);
		g_free(v->path);
		g_free(v->name);
	}
	g_array_free(s->devices, TRUE);
	g_array_free(s->saved, TRUE);
	g_free(s);
}

static void read_thread(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	struct snapshot *s = g_new0(struct snapshot, 1);
	s->devices = g_array_new(FALSE, TRUE, sizeof(struct device));
	s->saved = g_array_new(FALSE, TRUE, sizeof(struct saved));
	GVariant *r = g_dbus_connection_call_sync(nw.bus, NM, NM_PATH, NM,
		"GetDevices", NULL, G_VARIANT_TYPE("(ao)"), G_DBUS_CALL_FLAGS_NONE,
		2000, NULL, NULL);
	if (r) {
		s->ok = true;
		GVariantIter *iter;
		const char *path;
		g_variant_get(r, "(ao)", &iter);
		while (g_variant_iter_next(iter, "&o", &path)) {
			read_device(path, s);
		}
		g_variant_iter_free(iter);
		g_variant_unref(r);
		s->wifi_on = get_bool(NM_PATH, NM, "WirelessEnabled");
		s->wwan_on = get_bool(NM_PATH, NM, "WwanEnabled");
		read_saved(s);
		g_array_sort(s->saved, by_use);
	}
	g_task_return_pointer(task, s, snapshot_free);
}

/* Showing it */

static const char *kind(unsigned type) {
	return type == TYPE_WIFI ? "Wi-Fi" : type == TYPE_MODEM ?
		"Mobile broadband" : "Ethernet";
}

/* Stealth mode: each address of a list ("a/24, b/64") as a stand-in of
 * the same kind. On the main thread only, as the aliases are kept. */
static char *shown_addresses(const char *list) {
	if (list == NULL || !c8_stealth()) {
		return g_strdup(list);
	}
	char **parts = g_strsplit(list, ", ", -1);
	for (char **p = parts; *p; p++) {
		char *alias = g_strdup(c8_stealth_alias(C8_STEALTH_ADDRESS, *p));
		g_free(*p);
		*p = alias;
	}
	char *out = g_strjoinv(", ", parts);
	g_strfreev(parts);
	return out;
}

static char *status_text(const struct device *d) {
	const char *conn = d->conn ? c8_stealth_alias(d->type == TYPE_WIFI ?
		C8_STEALTH_WIFI : C8_STEALTH_DEVICE, d->conn) : NULL;
	if (d->state == STATE_ACTIVATED) {
		return g_strdup_printf("Connected to %s", conn ? conn : "a network");
	}
	if (d->state > STATE_DISCONNECTED && d->state < STATE_ACTIVATED) {
		return conn ? g_strdup_printf("Connecting to %s", conn) :
			g_strdup("Connecting");
	}
	if (d->state == STATE_DEACTIVATING) {
		return g_strdup("Disconnecting");
	}
	if (d->state == STATE_UNAVAILABLE) {
		return g_strdup(d->type == TYPE_ETHERNET ? "Cable unplugged" :
			d->type == TYPE_WIFI ? "Turned off" : "Not available");
	}
	if (d->state == STATE_FAILED) {
		return g_strdup("Couldn't connect");
	}
	return g_strdup("Not connected");
}

static void detail(struct c8ui_widget *grid, const char *name,
		const char *value) {
	if (value == NULL) {
		return;
	}
	struct c8ui_widget *n = c8ui_label_new(name, C8UI_TEXT_BODY);
	c8ui_label_set_color(n, C8UI_COLOR_SECONDARY);
	c8ui_widget_add(grid, n);
	struct c8ui_widget *v = c8ui_label_new(value, C8UI_TEXT_BODY);
	c8ui_label_set_max_lines(v, 4);
	v->fill = true;
	c8ui_widget_add(grid, v);
}

static void expanded(struct c8ui_widget *w, void *data) {
	const char *iface = w->user_data;
	if (c8ui_expander_get(w)) {
		g_hash_table_add(nw.open, g_strdup(iface));
	} else {
		g_hash_table_remove(nw.open, iface);
	}
}

static void expander_gone(struct c8ui_widget *w, void *data) {
	g_free(w->user_data);
}

static struct c8ui_widget *device_row(const struct device *d) {
	struct c8ui_widget *grid = c8ui_grid_new(2, 24, 8);
	c8ui_grid_set_column(grid, 1, 0, true);
	grid->fill = true;
	char buf[32];
	if (d->strength >= 0) {
		snprintf(buf, sizeof(buf), "%d%%", d->strength);
		detail(grid, "Signal", buf);
	}
	if (d->speed) {
		if (d->speed >= 1000 && d->speed % 1000 == 0) {
			snprintf(buf, sizeof(buf), "%u Gb/s", d->speed / 1000);
		} else {
			snprintf(buf, sizeof(buf), "%u Mb/s", d->speed);
		}
		detail(grid, "Speed", buf);
	}
	const char *const shown[][2] = {
		{ "IPv4 address", d->ip4 }, { "Gateway", d->gateway },
		{ "DNS servers", d->dns }, { "IPv6 address", d->ip6 },
		{ "Physical address", d->mac },
	};
	for (size_t i = 0; i < sizeof(shown) / sizeof(shown[0]); i++) {
		char *value = shown_addresses(shown[i][1]);
		detail(grid, shown[i][0], value);
		g_free(value);
	}
	detail(grid, "Adapter", d->iface);

	char *status = status_text(d);
	char *title = g_strdup_printf("%s · %s", kind(d->type), status);
	g_free(status);
	bool open = d->iface && g_hash_table_contains(nw.open, d->iface);
	struct c8ui_widget *e = c8ui_expander_new(title, grid, open, expanded,
		NULL);
	g_free(title);
	e->user_data = g_strdup(d->iface ? d->iface : "");
	e->on_destroy = expander_gone;
	e->fill = true;
	return e;
}

static void forget_done(GObject *source, GAsyncResult *res, gpointer data) {
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&error);
	if (r) {
		g_variant_unref(r);
	} else {
		show_error("Couldn't forget the network", error->message);
		g_error_free(error);
	}
}

static void forget(struct c8ui_widget *w, void *data) {
	const char *path = w->user_data;
	c8ui_widget_set_disabled(w, true);
	g_dbus_connection_call(nw.bus, NM, path, NM ".Settings.Connection",
		"Delete", NULL, NULL, G_DBUS_CALL_FLAGS_NONE, 5000, NULL, forget_done,
		NULL);
}

static void forget_gone(struct c8ui_widget *w, void *data) {
	g_free(w->user_data);
}

static struct c8ui_widget *saved_row(const struct saved *v) {
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	struct c8ui_widget *name = c8ui_label_new(
		c8_stealth_alias(C8_STEALTH_WIFI, v->name), C8UI_TEXT_BODY);
	name->fixed_width = 320;
	c8ui_widget_add(row, name);
	struct c8ui_widget *b = c8ui_button_new("Forget", forget, NULL);
	b->user_data = g_strdup(v->path);
	b->on_destroy = forget_gone;
	c8ui_widget_add(row, b);
	return row;
}

/* Every radio off, Bluetooth too: rfkill's, else NetworkManager's */
static void show_airplane(void) {
	struct snapshot *s = nw.now;
	if (nw.airplane == NULL) {
		return;
	}
	bool airplane = rfkill_any() ? rfkill_airplane() : s &&
		!s->wifi_on && (!s->has_wwan || !s->wwan_on);
	c8ui_toggle_set(nw.airplane, airplane);
	c8ui_widget_set_disabled(nw.airplane, !rfkill_any() && !(s && s->ok));
	nw.switched->hidden = !rfkill_switched_off();
}

static void radios_changed(void *data) {
	show_airplane();
	c8ui_widget_queue_layout(nw.page);
}

static void show(struct snapshot *s) {
	c8ui_widget_clear(nw.connections);
	if (!s->ok) {
		add(nw.connections, caption("NetworkManager isn't running, so there's "
			"nothing to show here."));
	} else if (s->devices->len == 0) {
		add(nw.connections, caption("This PC has no network adapters."));
	}
	for (guint i = 0; i < s->devices->len; i++) {
		add(nw.connections, device_row(&g_array_index(s->devices,
			struct device, i)));
	}
	show_airplane();
	c8ui_toggle_set(nw.wifi, s->wifi_on);
	nw.wifi->hidden = !s->has_wifi;
	c8ui_toggle_set(nw.wwan, s->wwan_on);
	nw.wwan->hidden = !s->has_wwan;

	c8ui_widget_clear(nw.known);
	if (s->saved->len == 0) {
		add(nw.known, caption("None yet. Networks you connect to are kept "
			"here."));
	}
	for (guint i = 0; i < s->saved->len; i++) {
		add(nw.known, saved_row(&g_array_index(s->saved, struct saved, i)));
	}
	c8ui_widget_queue_layout(nw.page);
}

static void refresh(void);

static void read_done(GObject *source, GAsyncResult *res, gpointer data) {
	struct snapshot *s = g_task_propagate_pointer(G_TASK(res), NULL);
	nw.reading = false;
	if (nw.page == NULL) {
		snapshot_free(s);
		return;
	}
	snapshot_free(nw.now);
	nw.now = s;
	show(s);
	if (nw.again) {
		nw.again = false;
		refresh();
	}
}

static void refresh(void) {
	if (nw.reading) {
		nw.again = true;
		return;
	}
	nw.reading = true;
	GTask *task = g_task_new(NULL, NULL, read_done, NULL);
	g_task_run_in_thread(task, read_thread);
	g_object_unref(task);
}

static gboolean settled(gpointer data) {
	nw.settle = 0;
	refresh();
	return G_SOURCE_REMOVE;
}

/* NetworkManager says a lot at once: read again when it pauses */
static void nm_changed(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data) {
	if (nw.settle) {
		g_source_remove(nw.settle);
	}
	nw.settle = g_timeout_add(SETTLE_MS, settled, NULL);
}

/* The radios */

static void set_done(GObject *source, GAsyncResult *res, gpointer data) {
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&error);
	if (r) {
		g_variant_unref(r);
	} else {
		show_error("Couldn't change that", error->message);
		g_error_free(error);
		refresh(); // back to how it is
	}
}

static void set_radio(const char *name, bool on) {
	g_dbus_connection_call(nw.bus, NM, NM_PATH,
		"org.freedesktop.DBus.Properties", "Set", g_variant_new("(ssv)", NM,
		name, g_variant_new_boolean(on)), NULL, G_DBUS_CALL_FLAGS_NONE, 5000,
		NULL, set_done, NULL);
}

static void airplane_changed(struct c8ui_widget *w, void *data) {
	bool on = c8ui_toggle_get(w);
	if (rfkill_any()) {
		rfkill_set_airplane(on);
		return;
	}
	set_radio("WirelessEnabled", !on);
	if (nw.now && nw.now->has_wwan) {
		set_radio("WwanEnabled", !on);
	}
}

static void radio_changed(struct c8ui_widget *w, void *data) {
	set_radio(data, c8ui_toggle_get(w));
}

static void page_gone(struct c8ui_widget *w, void *data) {
	nw.page = nw.connections = nw.airplane = nw.wifi = nw.wwan = NULL;
	nw.known = nw.switched = NULL;
	rfkill_unlisten(radios_changed, NULL);
	if (nw.sub) {
		g_dbus_connection_signal_unsubscribe(nw.bus, nw.sub);
		nw.sub = 0;
	}
	if (nw.settle) {
		g_source_remove(nw.settle);
		nw.settle = 0;
	}
	g_clear_pointer(&nw.now, snapshot_free);
}

static void network_build(struct c8ui_widget *box) {
	if (nw.bus == NULL) {
		nw.bus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, NULL);
		nw.open = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
	}
	nw.page = c8ui_box_new(C8UI_VERTICAL, 18);
	nw.page->fill = true;
	nw.page->on_destroy = page_gone;
	add(box, nw.page);

	add(nw.page, section_title("Connections"));
	nw.connections = c8ui_box_new(C8UI_VERTICAL, 12);
	nw.connections->fill = true;
	add(nw.page, nw.connections);
	add(nw.page, caption("To connect to a network, open Settings (Super+I) "
		"and choose the network icon."));

	add(nw.page, section_title("Airplane mode"));
	nw.airplane = c8ui_toggle_new(NULL, "Turn this on to stop all "
		"wireless communication: Wi-Fi, Bluetooth and mobile broadband.",
		false, airplane_changed, NULL);
	add(nw.page, nw.airplane);
	nw.switched = caption("A switch on the PC has turned a radio off. Use it "
		"to turn the radio back on.");
	nw.switched->hidden = true;
	add(nw.page, nw.switched);
	nw.wifi = c8ui_toggle_new("Wi-Fi", NULL, false, radio_changed,
		"WirelessEnabled");
	nw.wifi->hidden = true;
	add(nw.page, nw.wifi);
	nw.wwan = c8ui_toggle_new("Mobile broadband", NULL, false, radio_changed,
		"WwanEnabled");
	nw.wwan->hidden = true;
	add(nw.page, nw.wwan);

	add(nw.page, section_title("Known networks"));
	nw.known = c8ui_box_new(C8UI_VERTICAL, 8);
	nw.known->fill = true;
	add(nw.page, nw.known);

	if (nw.bus == NULL) {
		add(nw.connections, caption("Can't reach the system bus."));
		rfkill_listen(radios_changed, NULL);
		show_airplane();
		return;
	}
	rfkill_listen(radios_changed, NULL);
	show_airplane();
	nw.sub = g_dbus_connection_signal_subscribe(nw.bus, NM, NULL, NULL, NULL,
		NULL, G_DBUS_SIGNAL_FLAGS_NONE, nm_changed, NULL, NULL);
	refresh();
}

const struct page page_network = {
	.name = "network",
	.title = "Network",
	.build = network_build,
};
