/*
 * PC settings for the cont8nuum desktop.
 *
 * The compositor starts this program itself, over a private connection:
 * only then does it offer c8_settings_manager_v1, through which every
 * setting is read and changed.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon.h>
#include "cont8nuum-settings-v1-client-protocol.h"
#include "settings.h"

struct app app;

/* Kept in groups: the look and the machine, connections, input, accounts,
 * apps, then the rest */
static const struct page *page_list[] = {
	&page_personalise, &page_displays, &page_xr, &page_sound, &page_power,
	&page_network, &page_bluetooth,
	&page_mouse, &page_keyboard, &page_shortcuts,
	&page_accounts,
	&page_defaults, &page_startup,
	&page_general, &page_info,
};
#define PAGE_COUNT (sizeof(page_list) / sizeof(page_list[0]))

/* The settings */

static void free_entries(struct entry *entries, int count) {
	for (int i = 0; i < count; i++) {
		free(entries[i].section);
		free(entries[i].key);
		free(entries[i].value);
	}
	free(entries);
}

const char *setting(const char *section, const char *key) {
	for (int i = 0; i < app.count; i++) {
		if (strcmp(app.entries[i].section, section) == 0 &&
				strcmp(app.entries[i].key, key) == 0) {
			return app.entries[i].value;
		}
	}
	return NULL;
}

const char *setting_or(const char *section, const char *key, const char *def) {
	const char *v = setting(section, key);
	return v ? v : def;
}

bool setting_bool(const char *section, const char *key, bool def) {
	const char *v = setting(section, key);
	return v ? strcmp(v, "true") == 0 : def;
}

double setting_double(const char *section, const char *key, double def) {
	const char *v = setting(section, key);
	return v && v[0] ? strtod(v, NULL) : def;
}

int setting_all(const char *section, const char *key,
		const struct entry **out) {
	/* Entries of a key arrive together, so they're a run in the array */
	int first = -1, n = 0;
	for (int i = 0; i < app.count; i++) {
		if (strcmp(app.entries[i].section, section) == 0 &&
				(key == NULL || strcmp(app.entries[i].key, key) == 0)) {
			if (first < 0) {
				first = i;
			}
			if (i == first + n) {
				n++;
			}
		}
	}
	*out = first >= 0 ? &app.entries[first] : NULL;
	return n;
}

void setting_queue_set(const char *section, const char *key, const char *value) {
	c8_settings_v1_set(app.settings, section, key, value ? value : "");
}

void setting_queue_add(const char *section, const char *key, const char *value) {
	c8_settings_v1_add(app.settings, section, key, value ? value : "");
}

void setting_queue_remove(const char *section, const char *key) {
	c8_settings_v1_remove(app.settings, section, key ? key : "");
}

void setting_commit(void) {
	c8_settings_v1_commit(app.settings);
}

void setting_set(const char *section, const char *key, const char *value) {
	const char *now = setting(section, key);
	if (now && value && strcmp(now, value) == 0) {
		return;
	}
	setting_queue_set(section, key, value);
	setting_commit();
}

void setting_set_list(const char *section, const char *key,
		const char *const *values, int count) {
	setting_queue_remove(section, key);
	for (int i = 0; i < count; i++) {
		setting_queue_add(section, key, values[i]);
	}
	setting_commit();
}

/* The theme comes with the settings: apply it now rather than when the
 * files change on disk */
static void apply_theme(void) {
	struct c8ui_theme theme = *c8ui_root_theme(app.root);
	c8ui_parse_color(setting("appearance", "accent"), &theme.accent);
	c8ui_parse_color(setting("appearance", "background"), &theme.background);
	const char *font = setting("general", "font");
	if (font && font[0]) {
		theme.font = (char *)font;
	}
	c8ui_root_set_theme(app.root, &theme);
	c8ui_widget_set_background(app.nav_pane, theme.background);
}

static void settings_entry(void *data, struct c8_settings_v1 *settings,
		const char *section, const char *key, const char *value) {
	app.incoming = realloc(app.incoming,
		sizeof(*app.incoming) * (app.incoming_count + 1));
	app.incoming[app.incoming_count++] = (struct entry){
		strdup(section), strdup(key), strdup(value),
	};
}

/* A commit's failures come before its done; one dialog for them all */
static char failures[2048];

static void settings_failed(void *data, struct c8_settings_v1 *settings,
		const char *section, const char *key, const char *reason) {
	size_t len = strlen(failures);
	if (len >= sizeof(failures) - 1) {
		return;
	}
	snprintf(failures + len, sizeof(failures) - len, key[0] ?
		"%s%s (%s %s)" : "%s%s", len ? "\n" : "", reason, section, key);
}

static void show_failures(void) {
	if (failures[0]) {
		show_error("That didn't work", failures);
		failures[0] = '\0';
	}
}

static void bindings_refresh(void);

static void settings_done(void *data, struct c8_settings_v1 *settings) {
	free_entries(app.entries, app.count);
	app.entries = app.incoming;
	app.count = app.incoming_count;
	app.incoming = NULL;
	app.incoming_count = 0;
	app.ready = true;
	if (app.root) {
		apply_theme();
		bindings_refresh();
		if (app.content && app.page->refresh) {
			app.page->refresh();
		}
		show_failures();
	}
}

static const struct c8_settings_v1_listener settings_listener = {
	.entry = settings_entry,
	.done = settings_done,
	.failed = settings_failed,
};

/* Bound controls */

struct binding {
	struct c8ui_widget *widget;
	const char *section, *key;
	const char *format; // sliders
	double def;
	bool def_bool;
	const char *const *values; // choices: what each item saves
	int count, def_index;
	int (*index)(void); // bound_combo: the item to show
};

static struct binding **bindings;
static int binding_count, binding_cap;

static void binding_gone(struct c8ui_widget *w, void *data) {
	struct binding *b = data;
	for (int i = 0; i < binding_count; i++) {
		if (bindings[i] == b) {
			bindings[i] = bindings[--binding_count];
			break;
		}
	}
	free(b);
}

static struct binding *bind(struct c8ui_widget *w, const char *section,
		const char *key) {
	struct binding *b = calloc(1, sizeof(*b));
	b->widget = w;
	b->section = section;
	b->key = key;
	if (binding_count == binding_cap) {
		binding_cap = binding_cap ? binding_cap * 2 : 32;
		bindings = realloc(bindings, sizeof(*bindings) * binding_cap);
	}
	bindings[binding_count++] = b;
	w->user_data = b;
	w->on_destroy = binding_gone;
	return b;
}

/* Callbacks find their binding in the widget's user data */

static void toggle_changed(struct c8ui_widget *w, void *data) {
	struct binding *b = w->user_data;
	setting_set(b->section, b->key, c8ui_toggle_get(w) ? "true" : "false");
}

struct c8ui_widget *bound_toggle(const char *section, const char *key,
		const char *header, const char *caption_text, bool def) {
	struct c8ui_widget *w = c8ui_toggle_new(header, caption_text,
		setting_bool(section, key, def), toggle_changed, NULL);
	bind(w, section, key)->def_bool = def;
	return w;
}

static void slider_changed(struct c8ui_widget *w, void *data) {
	struct binding *b = w->user_data;
	if (c8ui_slider_is_live(w)) {
		return; /* only once let go */
	}
	char value[32];
	snprintf(value, sizeof(value), b->format, c8ui_slider_get(w));
	setting_set(b->section, b->key, value);
}

struct c8ui_widget *bound_slider(const char *section, const char *key,
		const char *header, double min, double max, double step, double def,
		const char *format) {
	struct c8ui_widget *w = c8ui_slider_new(header, min, max, step,
		setting_double(section, key, def), slider_changed, NULL);
	struct binding *b = bind(w, section, key);
	b->def = def;
	b->format = format;
	return w;
}

static void entry_done(struct c8ui_widget *w, void *data) {
	struct binding *b = w->user_data;
	setting_set(b->section, b->key, c8ui_entry_get(w));
}

struct c8ui_widget *bound_entry(const char *section, const char *key,
		const char *header, const char *placeholder) {
	struct c8ui_widget *w = c8ui_entry_new(header,
		setting_or(section, key, ""), entry_done, NULL);
	if (placeholder) {
		c8ui_entry_set_placeholder(w, placeholder);
	}
	bind(w, section, key);
	return w;
}

static int choice_index(struct binding *b) {
	const char *v = setting(b->section, b->key);
	for (int i = 0; v && i < b->count; i++) {
		if (strcmp(v, b->values[i]) == 0) {
			return i;
		}
	}
	return b->def_index;
}

static void choice_changed(struct c8ui_widget *w, void *data) {
	struct binding *b = w->user_data;
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < b->count) {
		setting_set(b->section, b->key, b->values[i]);
	}
}

struct c8ui_widget *bound_choice(const char *section, const char *key,
		const char *header, const char *const *values,
		const char *const *labels, int count, int def) {
	struct c8ui_widget *w = c8ui_combo_new(header, labels, count, 0,
		choice_changed, NULL);
	struct binding *b = bind(w, section, key);
	b->values = values;
	b->count = count;
	b->def_index = def;
	c8ui_combo_set(w, choice_index(b));
	return w;
}

struct c8ui_widget *bound_combo(struct c8ui_widget *combo, int (*index)(void)) {
	bind(combo, NULL, NULL)->index = index;
	return combo;
}

static void bindings_refresh(void) {
	for (int i = 0; i < binding_count; i++) {
		struct binding *b = bindings[i];
		struct c8ui_widget *w = b->widget;
		if (w->focused || w->pressed) {
			continue; /* being changed right now */
		}
		const char *name = w->impl->name;
		if (b->index) {
			c8ui_combo_set(w, b->index());
		} else if (strcmp(name, "toggle") == 0) {
			c8ui_toggle_set(w, setting_bool(b->section, b->key, b->def_bool));
		} else if (strcmp(name, "slider") == 0) {
			c8ui_slider_set(w, setting_double(b->section, b->key, b->def));
		} else if (strcmp(name, "combo") == 0 && b->values) {
			c8ui_combo_set(w, choice_index(b));
		} else if (strcmp(name, "entry") == 0) {
			const char *v = setting_or(b->section, b->key, "");
			if (strcmp(v, c8ui_entry_get(w)) != 0) {
				c8ui_entry_set(w, v);
			}
		}
	}
}

/* Pages */

void add(struct c8ui_widget *box, struct c8ui_widget *w) {
	c8ui_widget_add(box, w);
}

struct c8ui_widget *section_title(const char *text) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_box_set_padding(box, 0, 18, 0, 0);
	c8ui_widget_add(box, c8ui_label_new(text, C8UI_TEXT_SUBHEADER));
	return box;
}

struct c8ui_widget *caption(const char *text) {
	struct c8ui_widget *l = c8ui_label_new(text, C8UI_TEXT_BODY);
	c8ui_label_set_color(l, C8UI_COLOR_SECONDARY);
	return l;
}

void show_error(const char *title, const char *message) {
	c8ui_dialog_message(app.root, title, message);
}

/* The page list and a page beside it; narrow (snapped to a quarter, say)
 * one at a time, like a phone: the list, then a page over it with a back
 * button */
#define PANE_WIDTH 340

static struct c8ui_widget *pages_widget;

static void build_page(struct c8ui_widget *pages, struct c8ui_widget *content,
		void *data) {
	app.page = page_list[c8ui_pages_get(pages)];
	/* Cleared when it goes (back to the list), so refresh isn't called
	 * for a page that isn't there */
	c8ui_widget_track(content, &app.content);
	app.page->build(content);
}

static bool window_key(const struct c8ui_event *ev, void *data) {
	return ev->sym == XKB_KEY_Escape && c8ui_pages_back(pages_widget);
}

/* Stealth mode on or off: the open page is made again showing it */
static void stealth_flipped(void *data) {
	(void)data;
	if (app.content && pages_widget) {
		c8ui_pages_rebuild(pages_widget, false);
	}
}

static void build_window(int first, bool page_given) {
	c8_stealth_watch(stealth_flipped, NULL);
	pages_widget = c8ui_pages_new("PC settings", PANE_WIDTH, build_page, NULL);
	app.nav_pane = c8ui_pages_pane(pages_widget);
	for (size_t i = 0; i < PAGE_COUNT; i++) {
		c8ui_pages_add(pages_widget, page_list[i]->title);
	}
	c8ui_root_set_child(app.root, pages_widget);
	apply_theme();
	c8ui_root_set_key_handler(app.root, window_key, NULL);
	/* The page is built when the window gets its size (the pages' own
	 * doing, under 800 one at a time); one asked for by name shows
	 * even if that's narrow */
	if (page_given) {
		c8ui_pages_open(pages_widget, first);
	}
}

/* Main */

static struct c8_settings_manager_v1 *manager;

static void usage(FILE *f) {
	fprintf(f, "Usage: c8-settings [--page PAGE]\n\nPages:");
	for (size_t i = 0; i < PAGE_COUNT; i++) {
		fprintf(f, " %s", page_list[i]->name);
	}
	fprintf(f, "\n\nOpen it from cont8nuum: the PC settings tile, or Settings "
		"(Super+I) and then\nChange PC settings. Started any other way it "
		"can't reach the settings.\n");
}

int main(int argc, char *argv[]) {
	int first = 0;
	bool page_given = false;
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "--page") == 0 && i + 1 < argc) {
			const char *name = argv[++i];
			for (size_t p = 0; p < PAGE_COUNT; p++) {
				if (strcmp(page_list[p]->name, name) == 0) {
					first = (int)p;
					page_given = true;
				}
			}
		} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
			usage(stdout);
			return 0;
		} else {
			usage(stderr);
			return 2;
		}
	}

	app.ui = c8ui_app_new("c8-settings");
	if (app.ui == NULL) {
		fprintf(stderr, "c8-settings: cannot connect to a Wayland display\n");
		return EXIT_FAILURE;
	}
	manager = c8ui_app_bind(app.ui, &c8_settings_manager_v1_interface, 1);
	if (manager == NULL) {
		fprintf(stderr, "c8-settings: not started by cont8nuum, so the "
			"settings are out of reach.\n\n");
		usage(stderr);
		c8ui_app_destroy(app.ui);
		return EXIT_FAILURE;
	}
	app.settings = c8_settings_manager_v1_get_settings(manager);
	c8_settings_v1_add_listener(app.settings, &settings_listener, NULL);
	displays_init();
	struct wl_display *display = c8ui_app_display(app.ui);
	while (!app.ready && wl_display_dispatch(display) >= 0) {
		/* the first series of settings */
	}

	app.window = c8ui_window_new(app.ui, "PC settings", 1100, 720);
	app.root = c8ui_window_root(app.window);
	build_window(first, page_given);
	int status = c8ui_app_run(app.ui);

	c8_settings_v1_destroy(app.settings);
	c8_settings_manager_v1_destroy(manager);
	c8ui_app_destroy(app.ui);
	free_entries(app.entries, app.count);
	free(bindings);
	return status;
}
