/*
 * org.cont8nuum.Charms1 for c8ui apps: the app's search and settings
 * pages, served on the session bus under its app id. The shell calls;
 * this answers from what the app registered.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include "c8ui-charms.h"
#include "wayland-private.h"

#define PATH "/org/cont8nuum/Charms"
#define IFACE "org.cont8nuum.Charms1"

static const char introspection[] =
	"<node><interface name='org.cont8nuum.Charms1'>"
	"<method name='Search'><arg name='query' type='s' direction='in'/>"
	"<arg name='results' type='aa{sv}' direction='out'/></method>"
	"<method name='ActivateResult'><arg name='id' type='s' direction='in'/>"
	"<arg name='query' type='s' direction='in'/></method>"
	"<method name='Submit'><arg name='query' type='s' direction='in'/>"
	"</method>"
	"<method name='GetSettings'>"
	"<arg name='commands' type='a(sss)' direction='out'/></method>"
	"<method name='GetSettingsPage'>"
	"<arg name='command' type='s' direction='in'/>"
	"<arg name='controls' type='aa{sv}' direction='out'/></method>"
	"<method name='ActivateSettings'>"
	"<arg name='command' type='s' direction='in'/></method>"
	"<method name='SetSetting'><arg name='command' type='s' direction='in'/>"
	"<arg name='control' type='s' direction='in'/>"
	"<arg name='value' type='v' direction='in'/></method>"
	"<signal name='SettingsChanged'><arg name='command' type='s'/></signal>"
	"</interface></node>";

struct c8ui_setting {
	char *id, *type, *label, *description, *placeholder;
	bool password, enabled;
	char **items;
	double min, max, step;
	GVariant *value; // its type is what SetSetting must bring
	c8ui_setting_fn fn;
	void *data;
};

struct c8ui_settings_page {
	GPtrArray *settings; // struct c8ui_setting
	int headings; // for their made-up ids
};

struct page {
	char *id, *label;
	c8ui_page_fn build;
	c8ui_charms_fn action;
	void *data;
	/* As last built: SetSetting finds its control here */
	struct c8ui_settings_page *last;
};

struct c8ui_search {
	GDBusMethodInvocation *inv;
	GVariantBuilder results;
	bool held;
};

struct c8ui_charms {
	char *name;
	guint owner;
	GDBusConnection *bus;
	guint object;
	c8ui_search_fn search;
	c8ui_result_fn open;
	c8ui_submit_fn submit;
	void *search_data;
	GPtrArray *pages; // struct page
};

/* Pages and their controls */

static void setting_free(gpointer data) {
	struct c8ui_setting *s = data;
	free(s->id);
	free(s->type);
	free(s->label);
	free(s->description);
	free(s->placeholder);
	g_strfreev(s->items);
	if (s->value) {
		g_variant_unref(s->value);
	}
	free(s);
}

static void built_free(struct c8ui_settings_page *page) {
	if (page) {
		g_ptr_array_unref(page->settings);
		free(page);
	}
}

static void page_free(gpointer data) {
	struct page *p = data;
	free(p->id);
	free(p->label);
	built_free(p->last);
	free(p);
}

static char *dup_or_null(const char *s) {
	return s ? strdup(s) : NULL;
}

static struct c8ui_setting *add(struct c8ui_settings_page *page,
		const char *id, const char *type, const char *label,
		GVariant *value, c8ui_setting_fn fn, void *data) {
	struct c8ui_setting *s = calloc(1, sizeof(*s));
	s->id = strdup(id ? id : "");
	s->type = strdup(type);
	s->label = dup_or_null(label);
	s->enabled = true;
	s->value = value ? g_variant_ref_sink(value) : NULL;
	s->fn = fn;
	s->data = data;
	g_ptr_array_add(page->settings, s);
	return s;
}

static char **dup_items(const char *const *items, int count) {
	char **v = g_new0(char *, count + 1);
	for (int i = 0; i < count; i++) {
		v[i] = g_strdup(items[i]);
	}
	return v;
}

struct c8ui_setting *c8ui_page_toggle(struct c8ui_settings_page *page,
		const char *id, const char *label, bool on, c8ui_setting_fn fn,
		void *data) {
	return add(page, id, "toggle", label, g_variant_new_boolean(on), fn,
		data);
}

struct c8ui_setting *c8ui_page_choice(struct c8ui_settings_page *page,
		const char *id, const char *label, const char *const *items, int count,
		int selected, c8ui_setting_fn fn, void *data) {
	struct c8ui_setting *s = add(page, id, "choice", label,
		g_variant_new_int32(selected), fn, data);
	s->items = dup_items(items, count);
	return s;
}

struct c8ui_setting *c8ui_page_buttons(struct c8ui_settings_page *page,
		const char *id, const char *label, const char *const *items, int count,
		int selected, c8ui_setting_fn fn, void *data) {
	struct c8ui_setting *s = c8ui_page_choice(page, id, label, items, count,
		selected, fn, data);
	free(s->type);
	s->type = strdup("buttons");
	return s;
}

struct c8ui_setting *c8ui_page_slider(struct c8ui_settings_page *page,
		const char *id, const char *label, double min, double max, double step,
		double value, c8ui_setting_fn fn, void *data) {
	struct c8ui_setting *s = add(page, id, "slider", label,
		g_variant_new_double(value), fn, data);
	s->min = min;
	s->max = max;
	s->step = step;
	return s;
}

struct c8ui_setting *c8ui_page_text(struct c8ui_settings_page *page,
		const char *id, const char *label, const char *text, c8ui_setting_fn fn,
		void *data) {
	return add(page, id, "text", label, g_variant_new_string(text ? text : ""),
		fn, data);
}

struct c8ui_setting *c8ui_page_button(struct c8ui_settings_page *page,
		const char *id, const char *label, c8ui_setting_fn fn, void *data) {
	return add(page, id, "button", label, g_variant_new_boolean(true), fn,
		data);
}

struct c8ui_setting *c8ui_page_link(struct c8ui_settings_page *page,
		const char *id, const char *label, c8ui_setting_fn fn, void *data) {
	return add(page, id, "link", label, g_variant_new_boolean(true), fn, data);
}

static void text_block(struct c8ui_settings_page *page, const char *type,
		const char *text) {
	/* The shell keeps a page in place when the ids come back the same, so
	 * these are numbered in order rather than left blank */
	char id[32];
	snprintf(id, sizeof(id), "_%s%d", type, ++page->headings);
	add(page, id, type, text, NULL, NULL, NULL);
}

void c8ui_page_heading(struct c8ui_settings_page *page, const char *text) {
	text_block(page, "heading", text);
}

void c8ui_page_paragraph(struct c8ui_settings_page *page, const char *text) {
	text_block(page, "paragraph", text);
}

void c8ui_setting_set_description(struct c8ui_setting *s, const char *text) {
	free(s->description);
	s->description = dup_or_null(text);
}

void c8ui_setting_set_placeholder(struct c8ui_setting *s, const char *text) {
	free(s->placeholder);
	s->placeholder = dup_or_null(text);
}

void c8ui_setting_set_password(struct c8ui_setting *s, bool password) {
	s->password = password;
}

void c8ui_setting_set_enabled(struct c8ui_setting *s, bool enabled) {
	s->enabled = enabled;
}

const char *c8ui_setting_id(struct c8ui_setting *s) {
	return s->id;
}

bool c8ui_setting_get_bool(struct c8ui_setting *s) {
	return s->value && g_variant_is_of_type(s->value, G_VARIANT_TYPE_BOOLEAN) &&
		g_variant_get_boolean(s->value);
}

int c8ui_setting_get_int(struct c8ui_setting *s) {
	return s->value && g_variant_is_of_type(s->value, G_VARIANT_TYPE_INT32) ?
		g_variant_get_int32(s->value) : 0;
}

double c8ui_setting_get_double(struct c8ui_setting *s) {
	return s->value && g_variant_is_of_type(s->value, G_VARIANT_TYPE_DOUBLE) ?
		g_variant_get_double(s->value) : 0;
}

const char *c8ui_setting_get_text(struct c8ui_setting *s) {
	return s->value && g_variant_is_of_type(s->value, G_VARIANT_TYPE_STRING) ?
		g_variant_get_string(s->value, NULL) : "";
}

static struct page *find_page(struct c8ui_charms *ch, const char *id) {
	for (guint i = 0; i < ch->pages->len; i++) {
		struct page *p = ch->pages->pdata[i];
		if (strcmp(p->id, id) == 0) {
			return p;
		}
	}
	return NULL;
}

static void build(struct page *p) {
	built_free(p->last);
	p->last = calloc(1, sizeof(*p->last));
	p->last->settings = g_ptr_array_new_with_free_func(setting_free);
	p->build(p->last, p->data);
}

static GVariant *page_variant(struct c8ui_settings_page *page) {
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("aa{sv}"));
	for (guint i = 0; i < page->settings->len; i++) {
		struct c8ui_setting *s = page->settings->pdata[i];
		g_variant_builder_open(&b, G_VARIANT_TYPE("a{sv}"));
		g_variant_builder_add(&b, "{sv}", "id", g_variant_new_string(s->id));
		g_variant_builder_add(&b, "{sv}", "type",
			g_variant_new_string(s->type));
		if (s->label) {
			g_variant_builder_add(&b, "{sv}", "label",
				g_variant_new_string(s->label));
		}
		if (s->description) {
			g_variant_builder_add(&b, "{sv}", "description",
				g_variant_new_string(s->description));
		}
		if (s->placeholder) {
			g_variant_builder_add(&b, "{sv}", "placeholder",
				g_variant_new_string(s->placeholder));
		}
		if (s->password) {
			g_variant_builder_add(&b, "{sv}", "password",
				g_variant_new_boolean(true));
		}
		if (!s->enabled) {
			g_variant_builder_add(&b, "{sv}", "enabled",
				g_variant_new_boolean(false));
		}
		if (s->items) {
			g_variant_builder_add(&b, "{sv}", "options",
				g_variant_new_strv((const char *const *)s->items, -1));
		}
		if (strcmp(s->type, "slider") == 0) {
			g_variant_builder_add(&b, "{sv}", "min",
				g_variant_new_double(s->min));
			g_variant_builder_add(&b, "{sv}", "max",
				g_variant_new_double(s->max));
			g_variant_builder_add(&b, "{sv}", "step",
				g_variant_new_double(s->step));
		}
		/* A button's value is only what SetSetting brings */
		if (s->value && strcmp(s->type, "button") != 0 &&
				strcmp(s->type, "link") != 0) {
			g_variant_builder_add(&b, "{sv}", "value", s->value);
		}
		g_variant_builder_close(&b);
	}
	return g_variant_new("(aa{sv})", &b);
}

/* Search */

void c8ui_search_add(struct c8ui_search *search, const char *id,
		const char *title, const char *subtitle, const char *icon) {
	if (id == NULL || title == NULL) {
		return;
	}
	GVariantBuilder *b = &search->results;
	g_variant_builder_open(b, G_VARIANT_TYPE("a{sv}"));
	g_variant_builder_add(b, "{sv}", "id", g_variant_new_string(id));
	g_variant_builder_add(b, "{sv}", "title", g_variant_new_string(title));
	if (subtitle) {
		g_variant_builder_add(b, "{sv}", "subtitle",
			g_variant_new_string(subtitle));
	}
	if (icon) {
		g_variant_builder_add(b, "{sv}", "icon", g_variant_new_string(icon));
	}
	g_variant_builder_close(b);
}

void c8ui_search_hold(struct c8ui_search *search) {
	search->held = true;
}

void c8ui_search_done(struct c8ui_search *search) {
	g_dbus_method_invocation_return_value(search->inv,
		g_variant_new("(aa{sv})", &search->results));
	free(search);
}

/* The bus */

static void unknown(GDBusMethodInvocation *inv) {
	g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
		G_DBUS_ERROR_UNKNOWN_METHOD, "Not offered by this app");
}

static void set_setting(struct c8ui_charms *ch, GDBusMethodInvocation *inv,
		const char *command, const char *control, GVariant *value) {
	struct page *p = find_page(ch, command);
	if (p == NULL || p->build == NULL) {
		g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
			G_DBUS_ERROR_INVALID_ARGS, "No page %s", command);
		return;
	}
	if (p->last == NULL) {
		build(p);
	}
	struct c8ui_setting *s = NULL;
	for (guint i = 0; i < p->last->settings->len && s == NULL; i++) {
		struct c8ui_setting *t = p->last->settings->pdata[i];
		if (strcmp(t->id, control) == 0) {
			s = t;
		}
	}
	if (s == NULL || s->value == NULL ||
			!g_variant_is_of_type(value, g_variant_get_type(s->value))) {
		g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
			G_DBUS_ERROR_INVALID_ARGS, "No control %s of that type", control);
		return;
	}
	g_variant_unref(s->value);
	s->value = g_variant_ref(value);
	/* Answer first: fn may take a while, or ask for the page again */
	g_dbus_method_invocation_return_value(inv, NULL);
	if (s->fn) {
		s->fn(s, s->data);
	}
}

static void method_call(GDBusConnection *conn, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *inv, gpointer data) {
	struct c8ui_charms *ch = data;
	const char *a, *b;
	if (strcmp(method, "Search") == 0) {
		if (ch->search == NULL) {
			unknown(inv);
			return;
		}
		g_variant_get(params, "(&s)", &a);
		struct c8ui_search *search = calloc(1, sizeof(*search));
		search->inv = inv;
		g_variant_builder_init(&search->results, G_VARIANT_TYPE("aa{sv}"));
		ch->search(search, a, ch->search_data);
		if (!search->held) {
			c8ui_search_done(search);
		}
	} else if (strcmp(method, "ActivateResult") == 0) {
		if (ch->open == NULL) {
			unknown(inv);
			return;
		}
		g_variant_get(params, "(&s&s)", &a, &b);
		g_dbus_method_invocation_return_value(inv, NULL);
		ch->open(a, b, ch->search_data);
	} else if (strcmp(method, "Submit") == 0) {
		if (ch->submit == NULL) {
			unknown(inv);
			return;
		}
		g_variant_get(params, "(&s)", &a);
		g_dbus_method_invocation_return_value(inv, NULL);
		ch->submit(a, ch->search_data);
	} else if (strcmp(method, "GetSettings") == 0) {
		if (ch->pages->len == 0) {
			unknown(inv);
			return;
		}
		GVariantBuilder list;
		g_variant_builder_init(&list, G_VARIANT_TYPE("a(sss)"));
		for (guint i = 0; i < ch->pages->len; i++) {
			struct page *p = ch->pages->pdata[i];
			g_variant_builder_add(&list, "(sss)", p->id, p->label,
				p->build ? "page" : "action");
		}
		g_dbus_method_invocation_return_value(inv,
			g_variant_new("(a(sss))", &list));
	} else if (strcmp(method, "GetSettingsPage") == 0) {
		g_variant_get(params, "(&s)", &a);
		struct page *p = find_page(ch, a);
		if (p == NULL || p->build == NULL) {
			g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
				G_DBUS_ERROR_INVALID_ARGS, "No page %s", a);
			return;
		}
		build(p);
		g_dbus_method_invocation_return_value(inv, page_variant(p->last));
	} else if (strcmp(method, "ActivateSettings") == 0) {
		g_variant_get(params, "(&s)", &a);
		struct page *p = find_page(ch, a);
		if (p == NULL || p->action == NULL) {
			g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
				G_DBUS_ERROR_INVALID_ARGS, "No action %s", a);
			return;
		}
		g_dbus_method_invocation_return_value(inv, NULL);
		p->action(p->data);
	} else if (strcmp(method, "SetSetting") == 0) {
		GVariant *v;
		g_variant_get(params, "(&s&sv)", &a, &b, &v);
		set_setting(ch, inv, a, b, v);
		g_variant_unref(v);
	} else {
		unknown(inv);
	}
}

static const GDBusInterfaceVTable vtable = { .method_call = method_call };

static void bus_acquired(GDBusConnection *conn, const char *name,
		gpointer data) {
	struct c8ui_charms *ch = data;
	GError *error = NULL;
	GDBusNodeInfo *info = g_dbus_node_info_new_for_xml(introspection, NULL);
	ch->bus = g_object_ref(conn);
	ch->object = g_dbus_connection_register_object(conn, PATH,
		info->interfaces[0], &vtable, ch, NULL, &error);
	if (ch->object == 0) {
		fprintf(stderr, "%s: no charms: %s\n", ch->name, error->message);
		g_error_free(error);
	}
	g_dbus_node_info_unref(info);
}

static void name_lost(GDBusConnection *conn, const char *name,
		gpointer data) {
	/* Only when the bus goes. Another copy of the app having the name is
	 * fine: this one waits in the queue for it, and the shell finds each
	 * copy there by the pid of the window in front. */
}

struct c8ui_charms *c8ui_charms_new(struct c8ui_app *app) {
	const char *name = c8ui_app_get_id(app);
	if (name == NULL || !g_dbus_is_name(name) || g_dbus_is_unique_name(name)) {
		fprintf(stderr, "%s: an app id like org.example.App is needed for "
			"charms\n", name ? name : "c8ui");
		return NULL;
	}
	struct c8ui_charms *ch = calloc(1, sizeof(*ch));
	ch->name = strdup(name);
	ch->pages = g_ptr_array_new_with_free_func(page_free);
	GDBusConnection *own = c8ui_app_unique_bus(app);
	if (own) {
		/* c8ui_app_main has the name already */
		bus_acquired(own, name, ch);
	} else {
		ch->owner = g_bus_own_name(G_BUS_TYPE_SESSION, name,
			G_BUS_NAME_OWNER_FLAGS_NONE, bus_acquired, NULL, name_lost, ch,
			NULL);
	}
	return ch;
}

void c8ui_charms_destroy(struct c8ui_charms *ch) {
	if (ch == NULL) {
		return;
	}
	if (ch->object) {
		g_dbus_connection_unregister_object(ch->bus, ch->object);
	}
	if (ch->owner) {
		g_bus_unown_name(ch->owner);
	}
	if (ch->bus) {
		g_object_unref(ch->bus);
	}
	g_ptr_array_unref(ch->pages);
	free(ch->name);
	free(ch);
}

void c8ui_charms_on_search(struct c8ui_charms *ch, c8ui_search_fn search,
		c8ui_result_fn open, c8ui_submit_fn submit, void *data) {
	ch->search = search;
	ch->open = open;
	ch->submit = submit;
	ch->search_data = data;
}

static struct page *add_page(struct c8ui_charms *ch, const char *id,
		const char *label, void *data) {
	struct page *p = find_page(ch, id);
	if (p == NULL) {
		p = calloc(1, sizeof(*p));
		p->id = strdup(id);
		g_ptr_array_add(ch->pages, p);
	}
	free(p->label);
	p->label = strdup(label);
	p->data = data;
	return p;
}

void c8ui_charms_add_page(struct c8ui_charms *ch, const char *id,
		const char *label, c8ui_page_fn build, void *data) {
	struct page *p = add_page(ch, id, label, data);
	p->build = build;
	p->action = NULL;
	c8ui_charms_changed(ch, NULL);
}

void c8ui_charms_add_action(struct c8ui_charms *ch, const char *id,
		const char *label, c8ui_charms_fn fn, void *data) {
	struct page *p = add_page(ch, id, label, data);
	p->action = fn;
	p->build = NULL;
	c8ui_charms_changed(ch, NULL);
}

void c8ui_charms_changed(struct c8ui_charms *ch, const char *page) {
	if (ch->bus == NULL) {
		return; // nobody can have asked yet
	}
	g_dbus_connection_emit_signal(ch->bus, NULL, PATH, IFACE,
		"SettingsChanged", g_variant_new("(s)", page ? page : ""), NULL);
}
