#define _GNU_SOURCE
#include <gio/gio.h>
#include <signal.h>
#include <stdarg.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "tiles.h"
#include "stealth.h"
#include "widget.h"

static const struct widget_kind *kinds[] = {
	&kind_clock, &kind_calendar, &kind_clocks, &kind_weather,
	&kind_processor, &kind_memory, &kind_storage, &kind_network,
	&kind_battery, &kind_sensors, &kind_updates, &kind_nowplaying,
	&kind_volume, &kind_power, &kind_script,
};

struct content {
	GHashTable *fields;
};

static struct {
	struct widget widget;
	const char *tile_id;
	const char *color; // --color, or NULL for the tile's own
	GDBusConnection *bus;
	bool shell_up;
	GVariant *sent; // the last content sent, to skip repeats
	guint update_idle, tick_source;
	GMainLoop *loop;
} app;

/* The clock setting, from config.ini's [general] section; the file is
 * read again whenever its time stamp moves (PC settings rewrites it) */
const char *clock_mode(void) {
	static char mode[8];
	static char *path;
	static time_t seen = -1;
	if (path == NULL) {
		path = g_build_filename(g_get_user_config_dir(), "cont8nuum",
			"config.ini", NULL);
	}
	struct stat st;
	time_t mtime = stat(path, &st) == 0 ? st.st_mtime : 0;
	if (mtime == seen) {
		return mode;
	}
	seen = mtime;
	snprintf(mode, sizeof(mode), "auto");
	char *text = NULL;
	if (!g_file_get_contents(path, &text, NULL, NULL)) {
		return mode;
	}
	bool general = false;
	for (char *line = strtok(text, "\n"); line; line = strtok(NULL, "\n")) {
		g_strstrip(line);
		if (line[0] == '[') {
			general = strcmp(line, "[general]") == 0;
			continue;
		}
		char *eq = strchr(line, '=');
		if (!general || line[0] == '#' || eq == NULL) {
			continue;
		}
		*eq = '\0';
		if (strcmp(g_strstrip(line), "clock") == 0) {
			snprintf(mode, sizeof(mode), "%s", g_strstrip(eq + 1));
		}
	}
	g_free(text);
	return mode;
}

/* Content */

void set(struct content *c, const char *key, const char *fmt, ...) {
	va_list ap;
	va_start(ap, fmt);
	char *value = g_strdup_vprintf(fmt, ap);
	va_end(ap);
	if (value[0] == '\0') {
		g_free(value);
		g_hash_table_remove(c->fields, key);
		return;
	}
	g_hash_table_insert(c->fields, g_strdup(key), value);
}

static GVariant *build(void) {
	struct content c = {
		g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free),
	};
	app.widget.kind->content(&app.widget, &c);
	if (app.color && !g_hash_table_contains(c.fields, "color")) {
		set(&c, "color", "%s", app.color);
	}
	/* Sorted, so the same content compares equal */
	GList *keys = g_list_sort(g_hash_table_get_keys(c.fields),
		(GCompareFunc)strcmp);
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
	for (GList *k = keys; k; k = k->next) {
		g_variant_builder_add(&b, "{ss}", k->data,
			g_hash_table_lookup(c.fields, k->data));
	}
	g_list_free(keys);
	g_hash_table_destroy(c.fields);
	return g_variant_ref_sink(g_variant_builder_end(&b));
}

static void send_now(bool force) {
	if (app.bus == NULL || !app.shell_up) {
		return;
	}
	GVariant *content = build();
	if (!force && app.sent && g_variant_equal(content, app.sent)) {
		g_variant_unref(content);
		return;
	}
	if (app.sent) {
		g_variant_unref(app.sent);
	}
	app.sent = content;
	g_dbus_connection_call(app.bus, C8_TILES_NAME, C8_TILES_PATH,
		C8_TILES_IFACE, "Update",
		g_variant_new("(ss@a{ss})", app.tile_id, "", content), NULL,
		G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
}

static gboolean update_idle(gpointer data) {
	app.update_idle = 0;
	send_now(false);
	return G_SOURCE_REMOVE;
}

void widget_update(struct widget *w) {
	if (app.update_idle == 0) {
		app.update_idle = g_idle_add(update_idle, NULL);
	}
}

/* Ticking, only while Start shows */

static gboolean tick(gpointer data) {
	struct widget *w = &app.widget;
	w->kind->tick(w);
	return G_SOURCE_CONTINUE;
}

static void set_visible(bool visible) {
	struct widget *w = &app.widget;
	w->visible = visible;
	if (w->kind->tick == NULL) {
		return;
	}
	if (visible && app.tick_source == 0) {
		w->kind->tick(w);
		app.tick_source = g_timeout_add(w->kind->tick_ms, tick, NULL);
	} else if (!visible && app.tick_source != 0) {
		g_source_remove(app.tick_source);
		app.tick_source = 0;
	}
}

/* The shell */

static void leave(void *data) {
	g_main_loop_quit(app.loop);
}

/* A new shell (or the first): it may have lost what we sent */
static void shell_here(void *data) {
	app.shell_up = true;
	send_now(true);
}

static void shell_left(void *data) {
	app.shell_up = false;
}

static void start_visible(bool visible, void *data) {
	set_visible(visible);
}

/* Stealth mode on or off: the tile's names change (sent if they did) */
static void stealth_changed(void *data) {
	send_now(false);
}

static void tile_activated(void *data) {
	if (app.widget.kind->activated) {
		app.widget.kind->activated(&app.widget);
	}
}

/* A widget only lives on its tile: unpinned, there's nothing to do. And
 * we may have started before the shell did. */
static struct c8_tile_provider provider = {
	.quit = leave,
	.quit_unpinned = true,
	.shell = shell_here,
	.gone = shell_left,
	.visible = start_visible,
	.activated = tile_activated,
	.wait_for_shell = true,
};

/* Main */

static void usage(FILE *f) {
	fprintf(f, "Usage: c8-widget KIND [options] [tile-id]\n"
		"\n"
		"Keeps a live tile on the cont8nuum Start screen up to date. The tile\n"
		"id defaults to the kind's name.\n"
		"\n"
		"Options:\n"
		"  --color #rrggbb   Use this colour instead of the tile's\n"
		"\n"
		"Kinds:\n");
	for (size_t i = 0; i < G_N_ELEMENTS(kinds); i++) {
		fprintf(f, "  %-11s %s\n", kinds[i]->name, kinds[i]->summary);
		if (kinds[i]->options) {
			fprintf(f, "%s", kinds[i]->options);
		}
	}
}

int main(int argc, char *argv[]) {
	/* Day and month names and the first day of the week, as the user's locale has them */
	setlocale(LC_TIME, "");
	if (argc < 2 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
		usage(argc < 2 ? stderr : stdout);
		return argc < 2 ? 2 : 0;
	}
	/* The Tailscale tile grew into c8-tailscale; a start.ini from before
	 * still says `c8-widget tailscale ID` */
	if (strcmp(argv[1], "tailscale") == 0) {
		const char *id = argc > 2 && argv[argc - 1][0] != '-' ? argv[argc - 1] :
			"tailscale";
		execlp("c8-tailscale-tile", "c8-tailscale-tile", id, (char *)NULL);
		fprintf(stderr, "c8-widget: the tailscale tile is c8-tailscale-tile "
			"now, which isn't installed\n");
		return EXIT_FAILURE;
	}
	struct widget *w = &app.widget;
	for (size_t i = 0; i < G_N_ELEMENTS(kinds); i++) {
		if (strcmp(argv[1], kinds[i]->name) == 0) {
			w->kind = kinds[i];
		}
	}
	if (w->kind == NULL) {
		fprintf(stderr, "c8-widget: unknown kind '%s'\n\n", argv[1]);
		usage(stderr);
		return 2;
	}
	w->visible = true; // until the shell says otherwise

	/* Pull out the shared options and the tile id; the rest is the kind's */
	app.tile_id = w->kind->name;
	char **rest = g_new0(char *, argc + 1);
	int nrest = 0;
	rest[nrest++] = argv[1];
	for (int i = 2; i < argc; i++) {
		if (strcmp(argv[i], "--color") == 0 && i + 1 < argc) {
			app.color = argv[++i];
		} else if (argv[i][0] == '-') {
			rest[nrest++] = argv[i];
			/* Every kind option takes a value */
			if (i + 1 < argc) {
				rest[nrest++] = argv[++i];
			}
		} else {
			app.tile_id = argv[i];
		}
	}

	GError *err = NULL;
	app.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &err);
	if (app.bus == NULL) {
		fprintf(stderr, "c8-widget: no session bus: %s\n", err->message);
		g_error_free(err);
		return EXIT_FAILURE;
	}
	app.loop = g_main_loop_new(NULL, FALSE);
	if (w->kind->init && !w->kind->init(w, nrest, rest)) {
		usage(stderr);
		return 2;
	}

	provider.tile_id = app.tile_id;
	c8_tile_provider_watch(&provider, NULL);
	c8_stealth_watch(stealth_changed, NULL);
	signal(SIGPIPE, SIG_IGN);
	set_visible(true);

	g_main_loop_run(app.loop);
	g_dbus_connection_flush_sync(app.bus, NULL, NULL);
	g_free(rest);
	return EXIT_SUCCESS;
}

/* System helpers */

char *read_text(const char *path) {
	char *text = NULL;
	if (!g_file_get_contents(path, &text, NULL, NULL)) {
		return NULL;
	}
	return text;
}

bool read_long(const char *path, long *out) {
	char *text = read_text(path);
	if (text == NULL) {
		return false;
	}
	char *end;
	*out = strtol(text, &end, 10);
	bool ok = end != text;
	g_free(text);
	return ok;
}

void format_bytes(double bytes, char *buf, size_t len) {
	static const char units[] = "BKMGTP";
	int u = 0;
	while (bytes >= 1024 && u < 5) {
		bytes /= 1024;
		u++;
	}
	if (u == 0) {
		snprintf(buf, len, "%.0fB", bytes);
	} else if (bytes >= 100) {
		snprintf(buf, len, "%.0f%c", bytes, units[u]);
	} else if (bytes >= 10) {
		snprintf(buf, len, "%.1f%c", bytes, units[u]);
	} else {
		snprintf(buf, len, "%.2f%c", bytes, units[u]);
	}
}

struct command {
	struct widget *widget;
	command_done_fn done;
};

static void command_finished(GObject *source, GAsyncResult *result,
		gpointer data) {
	struct command *cmd = data;
	char *out = NULL;
	GError *err = NULL;
	if (!g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result,
			&out, NULL, &err) ||
			!g_subprocess_get_successful(G_SUBPROCESS(source))) {
		g_clear_error(&err);
		g_clear_pointer(&out, g_free);
	}
	cmd->done(cmd->widget, out);
	g_free(out);
	g_free(cmd);
	g_object_unref(source);
}

bool run_command(struct widget *w, const char *const *argv,
		command_done_fn done) {
	GError *err = NULL;
	GSubprocess *proc = g_subprocess_newv(argv,
		G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE, &err);
	if (proc == NULL) {
		g_clear_error(&err);
		return false;
	}
	struct command *cmd = g_new0(struct command, 1);
	cmd->widget = w;
	cmd->done = done;
	g_subprocess_communicate_utf8_async(proc, NULL, NULL, command_finished, cmd);
	return true;
}

bool have_program(const char *name) {
	char *path = g_find_program_in_path(name);
	g_free(path);
	return path != NULL;
}

char *cache_path(const char *name) {
	char *dir = g_build_filename(g_get_user_cache_dir(), "cont8nuum", NULL);
	g_mkdir_with_parents(dir, 0700);
	char *path = g_build_filename(dir, name, NULL);
	g_free(dir);
	return path;
}
