/*
 * The network and battery state the icons show. NetworkManager and
 * UPower are asked on a worker thread, a moment after any of their
 * properties change, so a slow system bus never holds up drawing.
 */
#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include "status.h"
#include "rfkill.h"
#include "stealth.h"

#define NM "org.freedesktop.NetworkManager"
#define NM_PATH "/org/freedesktop/NetworkManager"
#define UPOWER "org.freedesktop.UPower"
#define UPOWER_PATH "/org/freedesktop/UPower"
#define DISPLAY_DEVICE "/org/freedesktop/UPower/devices/DisplayDevice"
#define SETTLE_MS 250
#define MAX_LISTENERS 4

/* NetworkManager's numbers */
#define NM_DEVICE_TYPE_WIFI 2
#define NM_CONNECTIVITY_UNKNOWN 0
#define NM_CONNECTIVITY_FULL 4
/* UPower's */
#define UP_TYPE_BATTERY 2
#define UP_STATE_CHARGING 1
#define UP_STATE_PENDING_CHARGE 5

struct status status;

static struct {
	GDBusConnection *bus;
	struct {
		status_fn fn;
		void *data;
	} listeners[MAX_LISTENERS];
	int nlisteners;
	guint settle;
	bool busy, again;
	char *ap; // the access point in use, whose signals we hear
	guint ap_sub;
} s;

/* Reading properties, on the worker thread */

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

static guint32 prop_u(GDBusConnection *bus, const char *dest,
		const char *path, const char *iface, const char *name) {
	GVariant *v = prop(bus, dest, 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 prop_b(GDBusConnection *bus, const char *dest, const char *path,
		const char *iface, const char *name) {
	GVariant *v = prop(bus, dest, 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;
}

/* Strings and object paths, newly allocated, or NULL */
static char *prop_s(GDBusConnection *bus, const char *dest, const char *path,
		const char *iface, const char *name) {
	GVariant *v = prop(bus, dest, path, iface, name);
	char *str = NULL;
	if (v && (g_variant_is_of_type(v, G_VARIANT_TYPE_STRING) ||
			g_variant_is_of_type(v, G_VARIANT_TYPE_OBJECT_PATH))) {
		str = g_variant_dup_string(v, NULL);
	}
	if (v) {
		g_variant_unref(v);
	}
	return str;
}

static bool has_wifi(GDBusConnection *bus) {
	GVariant *r = g_dbus_connection_call_sync(bus, NM, NM_PATH, NM,
		"GetDevices", NULL, G_VARIANT_TYPE("(ao)"), G_DBUS_CALL_FLAGS_NONE,
		1000, NULL, NULL);
	if (r == NULL) {
		return false;
	}
	bool found = false;
	GVariantIter *it;
	const char *dev;
	g_variant_get(r, "(ao)", &it);
	while (!found && g_variant_iter_next(it, "&o", &dev)) {
		found = prop_u(bus, NM, dev, NM ".Device", "DeviceType") ==
			NM_DEVICE_TYPE_WIFI;
	}
	g_variant_iter_free(it);
	g_variant_unref(r);
	return found;
}

static void read_nm(GDBusConnection *bus, struct status *st) {
	GVariant *v = prop(bus, NM, NM_PATH, NM, "State");
	if (v == NULL) {
		st->net = STATUS_NET_UNKNOWN;
		return;
	}
	g_variant_unref(v);
	st->net = STATUS_NET_NONE;
	st->wifi_available = has_wifi(bus);
	st->airplane = st->wifi_available &&
		!prop_b(bus, NM, NM_PATH, NM, "WirelessEnabled");

	char *primary = prop_s(bus, NM, NM_PATH, NM, "PrimaryConnection");
	if (primary == NULL || strcmp(primary, "/") == 0) {
		g_free(primary);
		return;
	}
	const char *iface = NM ".Connection.Active";
	char *type = prop_s(bus, NM, primary, iface, "Type");
	st->net_name = prop_s(bus, NM, primary, iface, "Id");
	if (type == NULL) {
		st->net = STATUS_NET_OTHER;
	} else if (strcmp(type, "802-11-wireless") == 0) {
		st->net = STATUS_NET_WIFI;
		char *ap = prop_s(bus, NM, primary, iface, "SpecificObject");
		st->signal = ap ? (int)prop_u(bus, NM, ap, NM ".AccessPoint",
			"Strength") : 0;
		st->ap_path = ap;
	} else if (strcmp(type, "802-3-ethernet") == 0) {
		st->net = STATUS_NET_WIRED;
	} else if (strcmp(type, "gsm") == 0 || strcmp(type, "cdma") == 0) {
		st->net = STATUS_NET_MOBILE;
		st->signal = 100;
	} else {
		st->net = STATUS_NET_OTHER;
	}
	guint32 conn = prop_u(bus, NM, NM_PATH, NM, "Connectivity");
	st->limited = conn != NM_CONNECTIVITY_UNKNOWN &&
		conn != NM_CONNECTIVITY_FULL;
	g_free(type);
	g_free(primary);
}

static void read_upower(GDBusConnection *bus, struct status *st) {
	GVariant *r = g_dbus_connection_call_sync(bus, UPOWER, DISPLAY_DEVICE,
		"org.freedesktop.DBus.Properties", "GetAll",
		g_variant_new("(s)", UPOWER ".Device"), G_VARIANT_TYPE("(a{sv})"),
		G_DBUS_CALL_FLAGS_NONE, 1000, NULL, NULL);
	if (r == NULL) {
		return;
	}
	GVariant *props = g_variant_get_child_value(r, 0);
	gboolean present = FALSE;
	guint32 type = 0, state = 0;
	gdouble percent = 0;
	g_variant_lookup(props, "IsPresent", "b", &present);
	g_variant_lookup(props, "Type", "u", &type);
	g_variant_lookup(props, "State", "u", &state);
	g_variant_lookup(props, "Percentage", "d", &percent);
	g_variant_unref(props);
	g_variant_unref(r);
	st->battery = present && type == UP_TYPE_BATTERY;
	st->percent = (int)lround(percent);
	st->charging = state == UP_STATE_CHARGING ||
		state == UP_STATE_PENDING_CHARGE;
	st->on_battery = prop_b(bus, UPOWER, UPOWER_PATH, UPOWER, "OnBattery");
}

static void read_all(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	struct status *st = data;
	read_nm(s.bus, st);
	read_upower(s.bus, st);
	g_task_return_boolean(task, TRUE);
}

/* Back on the main thread */

static void free_status(gpointer data) {
	struct status *st = data;
	g_free(st->net_name);
	g_free(st->ap_path);
	g_free(st);
}

static bool same(const struct status *a, const struct status *b) {
	return a->net == b->net && a->limited == b->limited &&
		a->airplane == b->airplane &&
		a->wifi_available == b->wifi_available &&
		a->signal / 20 == b->signal / 20 &&
		g_strcmp0(a->net_name, b->net_name) == 0 &&
		a->battery == b->battery && a->percent == b->percent &&
		a->charging == b->charging && a->on_battery == b->on_battery;
}

static void refresh(void);

static void changed(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data);

/* Only the access point in use is listened to: a scan changes every one
 * in range many times over, and each signal woke us to read it all again */
/* It says something every few seconds (when it was last seen, its
 * strength to the percent): only a strength that moves a bar matters */
static void ap_changed(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data) {
	GVariant *props = NULL;
	guchar strength;
	if (g_variant_is_of_type(params, G_VARIANT_TYPE("(sa{sv}as)"))) {
		g_variant_get(params, "(@s@a{sv}@as)", NULL, &props, NULL);
	}
	bool moved = props && g_variant_lookup(props, "Strength", "y",
		&strength) && strength / 20 != status.signal / 20;
	if (props) {
		g_variant_unref(props);
	}
	if (moved) {
		changed(bus, sender, path, iface, signal, params, data);
	}
}

static void watch_ap(const char *ap) {
	if (g_strcmp0(ap, s.ap) == 0) {
		return;
	}
	if (s.ap_sub) {
		g_dbus_connection_signal_unsubscribe(s.bus, s.ap_sub);
		s.ap_sub = 0;
	}
	g_free(s.ap);
	s.ap = g_strdup(ap);
	if (ap && ap[0] == '/' && ap[1]) {
		s.ap_sub = g_dbus_connection_signal_subscribe(s.bus, NM,
			"org.freedesktop.DBus.Properties", "PropertiesChanged", ap,
			NM ".AccessPoint", G_DBUS_SIGNAL_FLAGS_NONE, ap_changed, NULL,
			NULL);
	}
}

static void read_done(GObject *source, GAsyncResult *res, gpointer data) {
	struct status *st = g_task_get_task_data(G_TASK(res));
	s.busy = false;
	watch_ap(st->ap_path);
	g_clear_pointer(&st->ap_path, g_free); // nobody else's
	/* Airplane mode is every radio off, Bluetooth too */
	if (rfkill_any()) {
		st->airplane = rfkill_airplane();
	}
	if (!same(st, &status)) {
		g_free(status.net_name);
		status = *st;
		st->net_name = NULL; /* status has it now */
		for (int i = 0; i < s.nlisteners; i++) {
			s.listeners[i].fn(s.listeners[i].data);
		}
	}
	if (s.again) {
		s.again = false;
		refresh();
	}
}

static void refresh(void) {
	if (s.busy) {
		s.again = true;
		return;
	}
	s.busy = true;
	GTask *task = g_task_new(NULL, NULL, read_done, NULL);
	g_task_set_task_data(task, g_new0(struct status, 1), free_status);
	g_task_run_in_thread(task, read_all);
	g_object_unref(task);
}

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

/* Scans change access points many times a second: wait for a pause */
static void changed(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data) {
	if (s.settle == 0) {
		s.settle = g_timeout_add(SETTLE_MS, settled, NULL);
	}
}

static void owner_changed(GDBusConnection *bus, const char *name,
		const char *owner, gpointer data) {
	changed(bus, NULL, NULL, NULL, NULL, NULL, NULL);
}

static void owner_gone(GDBusConnection *bus, const char *name, gpointer data) {
	changed(bus, NULL, NULL, NULL, NULL, NULL, NULL);
}

static void radios_changed(void *data) {
	refresh();
}

void status_init(void) {
	if (s.bus) {
		return;
	}
	s.bus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, NULL);
	if (s.bus == NULL) {
		return;
	}
	/* What the icons show and no more: NetworkManager itself (state,
	 * the connection in use, radios, devices coming and going), active
	 * connections, the access point in use (watch_ap), and UPower's
	 * summary of the batteries */
	const char *props = "org.freedesktop.DBus.Properties";
	g_dbus_connection_signal_subscribe(s.bus, NM, props,
		"PropertiesChanged", NM_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
		changed, NULL, NULL);
	g_dbus_connection_signal_subscribe(s.bus, NM, props,
		"PropertiesChanged", NULL, NM ".Connection.Active",
		G_DBUS_SIGNAL_FLAGS_NONE, changed, NULL, NULL);
	g_dbus_connection_signal_subscribe(s.bus, NM, NM, "StateChanged",
		NM_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE, changed, NULL, NULL);
	g_dbus_connection_signal_subscribe(s.bus, UPOWER, props,
		"PropertiesChanged", UPOWER_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
		changed, NULL, NULL);
	g_dbus_connection_signal_subscribe(s.bus, UPOWER, props,
		"PropertiesChanged", DISPLAY_DEVICE, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
		changed, NULL, NULL);
	/* Started or restarted after us */
	g_bus_watch_name_on_connection(s.bus, NM, G_BUS_NAME_WATCHER_FLAGS_NONE,
		owner_changed, owner_gone, NULL, NULL);
	g_bus_watch_name_on_connection(s.bus, UPOWER,
		G_BUS_NAME_WATCHER_FLAGS_NONE, owner_changed, owner_gone, NULL, NULL);
	rfkill_listen(radios_changed, NULL);
	refresh();
}

void status_listen(status_fn fn, void *data) {
	if (s.nlisteners < MAX_LISTENERS) {
		s.listeners[s.nlisteners].fn = fn;
		s.listeners[s.nlisteners].data = data;
		s.nlisteners++;
	}
}

/* Words */

const char *status_net_label(void) {
	if (status.airplane) {
		return "Airplane mode";
	}
	switch (status.net) {
	case STATUS_NET_UNKNOWN:
		return "Network";
	case STATUS_NET_NONE:
		return "Not connected";
	default:
		return status.net_name ? c8_stealth_alias(C8_STEALTH_WIFI,
			status.net_name) : "Connected";
	}
}

/* Icons, on a 24 × 24 grid */

static void dim_rect(cairo_t *cr, double x, double y, double w, double h,
		double alpha) {
	cairo_save(cr);
	cairo_rectangle(cr, x, y, w, h);
	cairo_clip(cr);
	cairo_paint_with_alpha(cr, alpha);
	cairo_restore(cr);
}

void status_draw_bars(cairo_t *cr, double x, double y, double size,
		int signal, bool dim) {
	double u = size / 24;
	int lit = dim || signal <= 0 ? 0 : (signal + 19) / 20;
	lit = lit > 5 ? 5 : lit;
	for (int i = 0; i < 5; i++) {
		double h = (4 + 4 * i) * u;
		double bx = x + (1.5 + 4.5 * i) * u, bottom = y + 22 * u;
		dim_rect(cr, bx, bottom - h, 3 * u, h, i < lit ? 1 : 0.35);
	}
}

static void draw_plane(cairo_t *cr, double x, double y, double u) {
	static const double pts[][2] = {
		{ 12, 1.5 }, { 13.3, 3 }, { 13.3, 9 }, { 22, 14 }, { 22, 16 },
		{ 13.3, 13.5 }, { 13.3, 19 }, { 16, 21 }, { 16, 22.5 }, { 12, 21.5 },
		{ 8, 22.5 }, { 8, 21 }, { 10.7, 19 }, { 10.7, 13.5 }, { 2, 16 },
		{ 2, 14 }, { 10.7, 9 }, { 10.7, 3 },
	};
	for (size_t i = 0; i < sizeof(pts) / sizeof(pts[0]); i++) {
		cairo_line_to(cr, x + pts[i][0] * u, y + pts[i][1] * u);
	}
	cairo_close_path(cr);
	cairo_fill(cr);
}

void status_draw_plane(cairo_t *cr, double x, double y, double size) {
	draw_plane(cr, x, y, size / 24);
}

static void draw_wired(cairo_t *cr, double x, double y, double u) {
	cairo_set_line_width(cr, 1.5 * u);
	cairo_rectangle(cr, x + 4.75 * u, y + 4.75 * u, 14.5 * u, 10 * u);
	cairo_stroke(cr);
	cairo_rectangle(cr, x + 10.5 * u, y + 15.5 * u, 3 * u, 3 * u);
	cairo_rectangle(cr, x + 7 * u, y + 18.5 * u, 10 * u, 1.5 * u);
	cairo_fill(cr);
}

/* Small marks in the top left corner, where the bars are short */
static void draw_cross(cairo_t *cr, double x, double y, double u) {
	cairo_save(cr);
	cairo_set_line_width(cr, 1.75 * u);
	cairo_move_to(cr, x + 2 * u, y + 2 * u);
	cairo_line_to(cr, x + 8 * u, y + 8 * u);
	cairo_move_to(cr, x + 8 * u, y + 2 * u);
	cairo_line_to(cr, x + 2 * u, y + 8 * u);
	cairo_stroke(cr);
	cairo_restore(cr);
}

static void draw_warning(cairo_t *cr, double x, double y, double u) {
	cairo_save(cr);
	cairo_move_to(cr, x + 6 * u, y + 0.5 * u);
	cairo_line_to(cr, x + 11.5 * u, y + 10 * u);
	cairo_line_to(cr, x + 0.5 * u, y + 10 * u);
	cairo_close_path(cr);
	cairo_set_source_rgb(cr, 0.94, 0.75, 0.04);
	cairo_fill(cr);
	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_rectangle(cr, x + 5.25 * u, y + 3.5 * u, 1.5 * u, 3.5 * u);
	cairo_rectangle(cr, x + 5.25 * u, y + 7.75 * u, 1.5 * u, 1.5 * u);
	cairo_fill(cr);
	cairo_restore(cr);
}

void status_draw_network(cairo_t *cr, double x, double y, double size) {
	double u = size / 24;
	if (status.airplane) {
		draw_plane(cr, x, y, u);
		return;
	}
	switch (status.net) {
	case STATUS_NET_UNKNOWN:
		return;
	case STATUS_NET_NONE:
		status_draw_bars(cr, x, y, size, 0, true);
		draw_cross(cr, x, y, u);
		return;
	case STATUS_NET_WIFI:
	case STATUS_NET_MOBILE:
		status_draw_bars(cr, x, y, size, status.signal > 0 ?
			status.signal : 1, false);
		break;
	default:
		draw_wired(cr, x, y, u);
		break;
	}
	if (status.limited) {
		draw_warning(cr, x, y, u);
	}
}

static bool status_battery_critical(void) {
	return status.battery && status.on_battery && !status.charging &&
		status.percent <= STATUS_BATTERY_CRITICAL;
}

void status_draw_battery(cairo_t *cr, double x, double y, double size,
		uint32_t bg) {
	if (!status.battery) {
		return;
	}
	double u = size / 24;
	cairo_save(cr);
	if (status_battery_critical()) {
		/* Too little left to see as a fill: all red, with a "!" */
		cairo_set_source_rgb(cr, 0.9, 0.08, 0);
		cairo_set_line_width(cr, 1.5 * u);
		cairo_rectangle(cr, x + 2.75 * u, y + 6.75 * u, 16.5 * u, 10.5 * u);
		cairo_stroke(cr);
		cairo_rectangle(cr, x + 20 * u, y + 10 * u, 2 * u, 4 * u);
		cairo_rectangle(cr, x + 10.1 * u, y + 8.5 * u, 1.8 * u, 4.5 * u);
		cairo_rectangle(cr, x + 10.1 * u, y + 13.7 * u, 1.8 * u, 1.8 * u);
		cairo_fill(cr);
		cairo_restore(cr);
		return;
	}
	cairo_set_line_width(cr, 1.5 * u);
	cairo_rectangle(cr, x + 2.75 * u, y + 6.75 * u, 16.5 * u, 10.5 * u);
	cairo_stroke(cr);
	cairo_rectangle(cr, x + 20 * u, y + 10 * u, 2 * u, 4 * u);
	cairo_fill(cr);
	int pct = status.percent < 0 ? 0 : status.percent > 100 ? 100 :
		status.percent;
	double fill = 13.5 * u * pct / 100;
	if (pct <= 10 && !status.charging) {
		cairo_set_source_rgb(cr, 0.9, 0.08, 0);
	}
	cairo_rectangle(cr, x + 4.25 * u, y + 8.25 * u, fill, 7.5 * u);
	cairo_fill(cr);
	cairo_restore(cr);
	if (status.charging) {
		/* A bolt, cut out of what's under it */
		static const double bolt[][2] = {
			{ 12.5, 3 }, { 6.5, 13 }, { 10.5, 13 }, { 9, 21 }, { 15.5, 10.5 },
			{ 11.5, 10.5 },
		};
		for (size_t i = 0; i < 6; i++) {
			cairo_line_to(cr, x + bolt[i][0] * u, y + bolt[i][1] * u);
		}
		cairo_close_path(cr);
		cairo_save(cr);
		cairo_set_source_rgb(cr, ((bg >> 16) & 0xff) / 255.0,
			((bg >> 8) & 0xff) / 255.0, (bg & 0xff) / 255.0);
		cairo_set_line_width(cr, 2 * u);
		cairo_stroke_preserve(cr);
		cairo_restore(cr);
		cairo_fill(cr);
	}
}
