#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include "widget.h"

/*
 * Power mode: power-profiles-daemon's active profile (tuned-ppd serves
 * the same interface). A click moves to the next mode it offers, the
 * same switch as the Settings flyout's Power menu and PC settings.
 */

#define PPD_NAME "org.freedesktop.UPower.PowerProfiles"
#define PPD_PATH "/org/freedesktop/UPower/PowerProfiles"

static const struct {
	const char *name, *label, *color;
} modes[] = {
	{ "power-saver", "Power saver", "#008a00" },
	{ "balanced", "Balanced", NULL },
	{ "performance", "Best performance", COLOR_WARN },
};

struct power {
	GDBusProxy *proxy;
	bool ready; // asked the bus, so a missing daemon is known
};

static bool offered(GDBusProxy *proxy, const char *name) {
	GVariant *list = g_dbus_proxy_get_cached_property(proxy, "Profiles");
	if (list == NULL) {
		return false;
	}
	bool found = false;
	GVariantIter iter;
	GVariant *dict;
	g_variant_iter_init(&iter, list);
	while (!found && (dict = g_variant_iter_next_value(&iter))) {
		const char *profile;
		if (g_variant_lookup(dict, "Profile", "&s", &profile)) {
			found = strcmp(profile, name) == 0;
		}
		g_variant_unref(dict);
	}
	g_variant_unref(list);
	return found;
}

/* Index into modes[] of the active one, or -1 */
static int active_mode(GDBusProxy *proxy) {
	GVariant *v = g_dbus_proxy_get_cached_property(proxy, "ActiveProfile");
	if (v == NULL) {
		return -1;
	}
	int found = -1;
	for (size_t i = 0; i < G_N_ELEMENTS(modes); i++) {
		if (strcmp(g_variant_get_string(v, NULL), modes[i].name) == 0) {
			found = i;
		}
	}
	g_variant_unref(v);
	return found;
}

/* The mode a click goes to, wrapping round; -1 if there's no choice */
static int next_mode(GDBusProxy *proxy, int from) {
	int n = G_N_ELEMENTS(modes);
	for (int step = 1; step < n; step++) {
		int i = ((from < 0 ? -1 : from) + step + n) % n;
		if (offered(proxy, modes[i].name)) {
			return i;
		}
	}
	return -1;
}

/* Why performance is held back: the daemon's reasons, in plain words */
static const char *degraded_reason(GDBusProxy *proxy, char *buf, size_t len) {
	GVariant *v = g_dbus_proxy_get_cached_property(proxy,
		"PerformanceDegraded");
	const char *reason = v ? g_variant_get_string(v, NULL) : "";
	const char *text = NULL;
	if (strstr(reason, "lap-detected")) {
		text = "limited: on your lap";
	} else if (strstr(reason, "high-operating-temperature")) {
		text = "limited: running hot";
	} else if (reason[0]) {
		text = "limited";
	}
	g_strlcpy(buf, text ? text : "", len);
	if (v) {
		g_variant_unref(v);
	}
	return buf;
}

/* An app holding a mode (a game through gamemode, say) */
static char *holder(GDBusProxy *proxy) {
	GVariant *holds = g_dbus_proxy_get_cached_property(proxy,
		"ActiveProfileHolds");
	if (holds == NULL) {
		return NULL;
	}
	char *who = NULL;
	if (g_variant_n_children(holds) > 0) {
		GVariant *dict = g_variant_get_child_value(holds, 0);
		const char *app;
		if (g_variant_lookup(dict, "ApplicationId", "&s", &app) && app[0]) {
			who = g_strdup(app);
		}
		g_variant_unref(dict);
	}
	g_variant_unref(holds);
	return who;
}

static void power_content(struct widget *w, struct content *c) {
	struct power *p = w->data;
	set(c, "label", "Power mode");
	if (!p->ready) {
		return;
	}
	int active = p->proxy ? active_mode(p->proxy) : -1;
	if (active < 0) {
		set(c, "heading", "Not available");
		set(c, "text1", "power-profiles-daemon isn't running");
		return;
	}
	set(c, "template", "text");
	set(c, "heading", "%s", modes[active].label);
	if (modes[active].color) {
		set(c, "color", "%s", modes[active].color);
	}
	int line = 1;
	char key[8], buf[64];
	char *who = holder(p->proxy);
	if (who) {
		snprintf(key, sizeof(key), "text%d", line++);
		set(c, key, "held by %s", who);
		g_free(who);
	}
	if (strcmp(modes[active].name, "performance") == 0 &&
			degraded_reason(p->proxy, buf, sizeof(buf))[0]) {
		snprintf(key, sizeof(key), "text%d", line++);
		set(c, key, "%s", buf);
	}
	int next = next_mode(p->proxy, active);
	if (next >= 0) {
		snprintf(key, sizeof(key), "text%d", line++);
		set(c, key, "Next: %s", modes[next].label);
	}
}

static void set_done(GObject *source, GAsyncResult *result, gpointer data) {
	GError *error = NULL;
	GVariant *ret = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), result,
		&error);
	if (ret) {
		g_variant_unref(ret);
	} else {
		g_warning("Can't change the power mode: %s", error->message);
		g_error_free(error);
	}
}

static void power_activated(struct widget *w) {
	struct power *p = w->data;
	if (p->proxy == NULL) {
		return;
	}
	int next = next_mode(p->proxy, active_mode(p->proxy));
	if (next < 0) {
		return;
	}
	/* The tile follows when the daemon says it changed */
	g_dbus_proxy_call(p->proxy, "org.freedesktop.DBus.Properties.Set",
		g_variant_new("(ssv)", PPD_NAME, "ActiveProfile",
		g_variant_new_string(modes[next].name)), G_DBUS_CALL_FLAGS_NONE, -1,
		NULL, set_done, NULL);
}

static void on_changed(GDBusProxy *proxy, GVariant *changed,
		const char *const *invalidated, gpointer data) {
	widget_update(data);
}

static void on_owner(GObject *proxy, GParamSpec *pspec, gpointer data) {
	widget_update(data);
}

static void got_proxy(GObject *source, GAsyncResult *result, gpointer data) {
	struct widget *w = data;
	struct power *p = w->data;
	GError *error = NULL;
	p->ready = true;
	p->proxy = g_dbus_proxy_new_for_bus_finish(result, &error);
	if (p->proxy == NULL) {
		g_warning("Power mode: %s", error->message);
		g_error_free(error);
	} else {
		g_signal_connect(p->proxy, "g-properties-changed",
			G_CALLBACK(on_changed), w);
		/* The daemon restarting comes back with fresh properties */
		g_signal_connect(p->proxy, "notify::g-name-owner",
			G_CALLBACK(on_owner), w);
	}
	widget_update(w);
}

static bool power_init(struct widget *w, int argc, char **argv) {
	w->data = g_new0(struct power, 1);
	g_dbus_proxy_new_for_bus(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, NULL,
		PPD_NAME, PPD_PATH, PPD_NAME, NULL, got_proxy, w);
	return true;
}

const struct widget_kind kind_power = {
	.name = "power",
	.summary = "Power mode; click for the next one",
	.init = power_init,
	.content = power_content,
	.activated = power_activated,
};
