/*
 * Power modes from power-profiles-daemon (or tuned-ppd, which serves the
 * same interface): power saver, balanced, performance. The Power tile's
 * menu shows them; the daemon lets the active session switch.
 */
#include <string.h>
#include <gio/gio.h>
#include "power-profiles.h"
#include "shell.h"

#define PPD_NAME C8_PPD_NAME
#define PPD_PATH C8_PPD_PATH

static GDBusProxy *proxy;

static void got_proxy(GObject *source, GAsyncResult *result, gpointer data) {
	GError *error = NULL;
	proxy = g_dbus_proxy_new_for_bus_finish(result, &error);
	if (proxy == NULL) {
		g_warning("Power modes: %s", error->message);
		g_error_free(error);
	}
}

void profiles_init(void) {
	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, NULL);
}

int profiles_list(const char **names, const char **labels, int max) {
	int n = 0;
	for (size_t i = 0; i < G_N_ELEMENTS(c8_power_profiles) && n < max; i++) {
		if (c8_power_profile_offered(proxy, c8_power_profiles[i].name)) {
			names[n] = c8_power_profiles[i].name;
			labels[n] = c8_power_profiles[i].label;
			n++;
		}
	}
	/* Only one mode is no choice */
	return n > 1 ? n : 0;
}

bool profiles_active(const char *name) {
	GVariant *v = proxy ? g_dbus_proxy_get_cached_property(proxy,
		"ActiveProfile") : NULL;
	bool active = v && strcmp(g_variant_get_string(v, NULL), name) == 0;
	if (v) {
		g_variant_unref(v);
	}
	return active;
}

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);
	}
}

void profiles_set(const char *name) {
	if (proxy == NULL) {
		return;
	}
	g_dbus_proxy_call(proxy, "org.freedesktop.DBus.Properties.Set",
		g_variant_new("(ssv)", PPD_NAME, "ActiveProfile",
		g_variant_new_string(name)), G_DBUS_CALL_FLAGS_NONE, -1, NULL,
		set_done, NULL);
}
