/*
 * Under the UI: timers, HTTP, JSON, running commands, a place to keep
 * settings, and live tiles (sending them, and being a tile's provider).
 * Nothing here blocks: answers come to a function later, on the main
 * loop.
 */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include "c8lua.h"
#include "http.h"
#include "json.h"
#include "tiles.h"

/* Timers: c8.after(seconds, fn) once, c8.every(seconds, fn) until fn
 * returns false; both return a timer with :cancel() */

#define TIMER_META "c8.timer"

struct timer {
	guint source; // 0: over
	int fn, self; // refs: the function, and the userdata while it runs
	bool repeat;
};

static void timer_over(lua_State *L, struct timer *t) {
	t->source = 0;
	c8l_unref(L, t->fn);
	t->fn = LUA_NOREF;
	int self = t->self;
	t->self = LUA_NOREF;
	c8l_unref(L, self); // may free t
}

static gboolean timer_fire(gpointer data) {
	lua_State *L = c8l;
	struct timer *t = data;
	bool again = false;
	/* Held while the function runs: it may cancel the timer, and the
	 * collector must not take it from under us */
	lua_rawgeti(L, LUA_REGISTRYINDEX, t->self);
	int held = lua_gettop(L);
	if (c8l_push_ref(L, t->fn)) {
		if (c8l_call(L, 0, 1)) {
			again = t->repeat && !(lua_isboolean(L, -1) &&
				!lua_toboolean(L, -1));
			lua_pop(L, 1);
		}
	}
	/* The function may have cancelled it */
	if (t->source == 0) {
		again = false;
	} else if (!again) {
		timer_over(L, t);
	}
	lua_settop(L, held - 1);
	return again ? G_SOURCE_CONTINUE : G_SOURCE_REMOVE;
}

static int timer_new(lua_State *L, bool repeat) {
	double seconds = luaL_checknumber(L, 1);
	luaL_checktype(L, 2, LUA_TFUNCTION);
	struct timer *t = lua_newuserdatauv(L, sizeof(*t), 0);
	luaL_setmetatable(L, TIMER_META);
	t->repeat = repeat;
	t->fn = c8l_ref(L, 2);
	lua_pushvalue(L, -1);
	t->self = luaL_ref(L, LUA_REGISTRYINDEX);
	t->source = g_timeout_add((guint)(MAX(seconds, 0) * 1000), timer_fire, t);
	return 1;
}

static int l_after(lua_State *L) {
	return timer_new(L, false);
}

static int l_every(lua_State *L) {
	return timer_new(L, true);
}

static int timer_cancel(lua_State *L) {
	struct timer *t = luaL_checkudata(L, 1, TIMER_META);
	if (t->source) {
		g_source_remove(t->source);
		timer_over(L, t);
	}
	return 0;
}

/* JSON */

static void *null_mark = &null_mark; // c8.null: a null in a list

static void push_json(lua_State *L, const struct json *j, int depth) {
	if (j == NULL || depth > 200) {
		lua_pushnil(L);
		return;
	}
	luaL_checkstack(L, 4, "JSON nested too deep");
	switch (j->type) {
	case JSON_BOOL:
		lua_pushboolean(L, j->boolean);
		break;
	case JSON_NUMBER:
		/* Whole numbers as integers, so ids print without ".0" */
		if (j->number == floor(j->number) && fabs(j->number) < 9e15) {
			lua_pushinteger(L, (lua_Integer)j->number);
		} else {
			lua_pushnumber(L, j->number);
		}
		break;
	case JSON_STRING:
		lua_pushstring(L, j->string ? j->string : "");
		break;
	case JSON_ARRAY: {
		lua_newtable(L);
		lua_Integer i = 1;
		for (const struct json *c = j->child; c; c = c->next) {
			if (c->type == JSON_NULL) {
				lua_pushlightuserdata(L, null_mark);
			} else {
				push_json(L, c, depth + 1);
			}
			lua_seti(L, -2, i++);
		}
		break;
	}
	case JSON_OBJECT:
		lua_newtable(L);
		for (const struct json *c = j->child; c; c = c->next) {
			if (c->key && c->type != JSON_NULL) {
				push_json(L, c, depth + 1);
				lua_setfield(L, -2, c->key);
			}
		}
		break;
	default:
		lua_pushnil(L);
	}
}

/* c8.json.decode(text): the value, or nil and "not JSON" */
static int l_json_decode(lua_State *L) {
	struct json *j = json_parse(luaL_checkstring(L, 1));
	if (j == NULL) {
		lua_pushnil(L);
		lua_pushliteral(L, "not JSON");
		return 2;
	}
	push_json(L, j, 0);
	json_free(j);
	return 1;
}

static void dump_string(GString *out, const char *s) {
	g_string_append_c(out, '"');
	for (const unsigned char *p = (const unsigned char *)s; *p; p++) {
		switch (*p) {
		case '"':
			g_string_append(out, "\\\"");
			break;
		case '\\':
			g_string_append(out, "\\\\");
			break;
		case '\n':
			g_string_append(out, "\\n");
			break;
		case '\r':
			g_string_append(out, "\\r");
			break;
		case '\t':
			g_string_append(out, "\\t");
			break;
		default:
			if (*p < 0x20) {
				g_string_append_printf(out, "\\u%04x", *p);
			} else {
				g_string_append_c(out, *p);
			}
		}
	}
	g_string_append_c(out, '"');
}

static void dump_value(lua_State *L, int index, GString *out, int depth) {
	index = lua_absindex(L, index);
	luaL_checkstack(L, 6, "too deep to write as JSON");
	switch (lua_type(L, index)) {
	case LUA_TBOOLEAN:
		g_string_append(out, lua_toboolean(L, index) ? "true" : "false");
		break;
	case LUA_TNUMBER:
		if (lua_isinteger(L, index)) {
			g_string_append_printf(out, "%lld",
				(long long)lua_tointeger(L, index));
		} else if (isfinite(lua_tonumber(L, index))) {
			char buf[G_ASCII_DTOSTR_BUF_SIZE];
			g_string_append(out, g_ascii_dtostr(buf, sizeof(buf),
				lua_tonumber(L, index)));
		} else {
			g_string_append(out, "null");
		}
		break;
	case LUA_TSTRING:
		dump_string(out, lua_tostring(L, index));
		break;
	case LUA_TTABLE: {
		if (depth > 100) {
			luaL_error(L, "too deep to write as JSON (a table in itself?)");
		}
		lua_Integer n = luaL_len(L, index);
		if (n > 0) {
			/* A list */
			g_string_append_c(out, '[');
			for (lua_Integer i = 1; i <= n; i++) {
				if (i > 1) {
					g_string_append_c(out, ',');
				}
				lua_geti(L, index, i);
				dump_value(L, -1, out, depth + 1);
				lua_pop(L, 1);
			}
			g_string_append_c(out, ']');
			break;
		}
		/* Keys in order, so the same table is the same text */
		GPtrArray *keys = g_ptr_array_new();
		lua_pushnil(L);
		while (lua_next(L, index)) {
			if (lua_type(L, -2) == LUA_TSTRING) {
				g_ptr_array_add(keys, (gpointer)lua_tostring(L, -2));
			}
			lua_pop(L, 1);
		}
		g_ptr_array_sort_values(keys, (GCompareFunc)strcmp);
		g_string_append_c(out, '{');
		for (guint i = 0; i < keys->len; i++) {
			if (i > 0) {
				g_string_append_c(out, ',');
			}
			dump_string(out, keys->pdata[i]);
			g_string_append_c(out, ':');
			lua_getfield(L, index, keys->pdata[i]);
			dump_value(L, -1, out, depth + 1);
			lua_pop(L, 1);
		}
		g_string_append_c(out, '}');
		g_ptr_array_free(keys, TRUE);
		break;
	}
	default:
		/* nil, c8.null, and what JSON has no word for */
		g_string_append(out, "null");
	}
}

/* c8.json.encode(value): text. A table with a first item is a list,
 * any other an object (an empty one too) */
static int l_json_encode(lua_State *L) {
	luaL_checkany(L, 1);
	GString *out = g_string_new(NULL);
	/* An error would leak `out`; only cycles and deep nesting raise one */
	dump_value(L, 1, out, 0);
	lua_pushlstring(L, out->str, out->len);
	g_string_free(out, TRUE);
	return 1;
}

/* HTTP: c8.http{ url, method, body, token, accept, dest, follow },
 * fn(status, body). status 0: the server wasn't reached. A table body
 * goes as JSON. */

static void http_done(int status, const char *body, void *data) {
	lua_State *L = c8l;
	int ref = GPOINTER_TO_INT(data);
	if (c8l_push_ref(L, ref)) {
		lua_pushinteger(L, status);
		lua_pushstring(L, body);
		c8l_call(L, 2, 0);
	}
	c8l_unref(L, ref);
}

static int l_http(lua_State *L) {
	if (lua_type(L, 1) == LUA_TSTRING) {
		lua_newtable(L);
		lua_pushvalue(L, 1);
		lua_setfield(L, -2, "url");
		lua_replace(L, 1);
	}
	luaL_checktype(L, 1, LUA_TTABLE);
	luaL_checktype(L, 2, LUA_TFUNCTION);
	const char *url = c8l_field_str(L, 1, "url", NULL);
	if (url == NULL) {
		return luaL_error(L, "c8.http needs a url");
	}
	char *json = NULL;
	lua_getfield(L, 1, "body");
	if (lua_istable(L, -1)) {
		GString *out = g_string_new(NULL);
		dump_value(L, -1, out, 0);
		json = g_string_free(out, FALSE);
	}
	lua_pop(L, 1);
	struct c8_http request = {
		.method = c8l_field_str(L, 1, "method", NULL),
		.url = url,
		.body = json ? json : c8l_field_str(L, 1, "body", NULL),
		.token = c8l_field_str(L, 1, "token", NULL),
		.accept = c8l_field_str(L, 1, "accept", NULL),
		.dest = c8l_field_str(L, 1, "dest", NULL),
		.agent = c8l_field_str(L, 1, "agent", "cont8nuum"),
		.follow = c8l_field_bool(L, 1, "follow", true),
		/* Plain http only where the script says so: a test server */
		.allow_http = c8l_field_bool(L, 1, "allow_http", false),
	};
	c8_http(&request, http_done, GINT_TO_POINTER(c8l_ref(L, 2)));
	g_free(json);
	return 0;
}

/* Commands: c8.run({ "tailscale", "status" } [, { input = text }],
 * fn(status, out, err)). status is the exit status, nil when it couldn't
 * be started (err says why) */

static void run_done(GObject *source, GAsyncResult *result, gpointer data) {
	lua_State *L = c8l;
	int ref = GPOINTER_TO_INT(data);
	GSubprocess *proc = G_SUBPROCESS(source);
	GBytes *out = NULL, *err = NULL;
	GError *error = NULL;
	g_subprocess_communicate_finish(proc, result, &out, &err, &error);
	if (c8l_push_ref(L, ref)) {
		if (error) {
			lua_pushnil(L);
			lua_pushliteral(L, "");
			lua_pushstring(L, error->message);
		} else {
			gsize n = 0;
			const char *p;
			lua_pushinteger(L, g_subprocess_get_if_exited(proc) ?
				g_subprocess_get_exit_status(proc) : -1);
			p = out ? g_bytes_get_data(out, &n) : NULL;
			lua_pushlstring(L, p ? p : "", p ? n : 0);
			p = err ? g_bytes_get_data(err, &n) : NULL;
			lua_pushlstring(L, p ? p : "", p ? n : 0);
		}
		c8l_call(L, 3, 0);
	}
	c8l_unref(L, ref);
	g_clear_error(&error);
	g_clear_pointer(&out, g_bytes_unref);
	g_clear_pointer(&err, g_bytes_unref);
	g_object_unref(proc);
}

static int l_run(lua_State *L) {
	luaL_checktype(L, 1, LUA_TTABLE);
	int fn = lua_isfunction(L, 2) ? 2 : 3;
	int count = 0;
	char **argv = c8l_strings(L, 1, NULL, &count);
	if (count == 0) {
		g_strfreev(argv);
		return luaL_error(L, "c8.run needs a command: { \"name\", ... }");
	}
	const char *input = lua_istable(L, 2) ?
		c8l_field_str(L, 2, "input", NULL) : NULL;
	GError *error = NULL;
	GSubprocess *proc = g_subprocess_newv((const char *const *)argv,
		G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_PIPE |
		(input ? G_SUBPROCESS_FLAGS_STDIN_PIPE : 0), &error);
	g_strfreev(argv);
	if (proc == NULL) {
		if (lua_isfunction(L, fn)) {
			lua_pushvalue(L, fn);
			lua_pushnil(L);
			lua_pushliteral(L, "");
			lua_pushstring(L, error->message);
			c8l_call(L, 3, 0);
		}
		g_error_free(error);
		return 0;
	}
	GBytes *in = input ? g_bytes_new(input, strlen(input)) : NULL;
	g_subprocess_communicate_async(proc, in, NULL, run_done,
		GINT_TO_POINTER(c8l_ref(L, fn)));
	g_clear_pointer(&in, g_bytes_unref);
	return 0;
}

/* Kept settings: c8.save("notes", value) writes it as JSON to
 * ~/.config/cont8nuum/notes.json, c8.load("notes") reads it back (nil
 * when there's none) */

static char *kept_path(lua_State *L, int index) {
	const char *name = luaL_checkstring(L, index);
	if (name[0] == '\0' || name[0] == '.' || strchr(name, '/')) {
		luaL_error(L, "a kept file's name is a plain word, like \"notes\"");
	}
	char *file = g_strconcat(name, ".json", NULL);
	char *path = g_build_filename(g_get_user_config_dir(), "cont8nuum", file,
		NULL);
	g_free(file);
	return path;
}

static int l_load(lua_State *L) {
	char *path = kept_path(L, 1);
	char *text = NULL;
	bool read = g_file_get_contents(path, &text, NULL, NULL);
	g_free(path);
	if (!read) {
		return 0;
	}
	struct json *j = json_parse(text);
	g_free(text);
	if (j == NULL) {
		return 0;
	}
	push_json(L, j, 0);
	json_free(j);
	return 1;
}

static int l_save(lua_State *L) {
	char *path = kept_path(L, 1);
	luaL_checkany(L, 2);
	GString *out = g_string_new(NULL);
	dump_value(L, 2, out, 0);
	char *dir = g_path_get_dirname(path);
	g_mkdir_with_parents(dir, 0700);
	g_free(dir);
	/* Only ours to read: an app may keep a key or a token here */
	bool ok = g_file_set_contents_full(path, out->str, out->len,
		G_FILE_SET_CONTENTS_CONSISTENT, 0600, NULL);
	g_string_free(out, TRUE);
	g_free(path);
	lua_pushboolean(L, ok);
	return 1;
}

/* Live tiles. Fields are those of org.cont8nuum.Tiles1 (template,
 * heading, text1.., block, image, color, expires, wide.FIELD, ...) */

static GVariant *tile_fields(lua_State *L, int index, char **badge) {
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
	index = lua_absindex(L, index);
	lua_pushnil(L);
	while (lua_next(L, index)) {
		if (lua_type(L, -2) == LUA_TSTRING) {
			const char *key = lua_tostring(L, -2);
			const char *value = luaL_tolstring(L, -1, NULL);
			if (strcmp(key, "badge") == 0 && badge) {
				*badge = g_strdup(value);
			} else if (strcmp(key, "tag") != 0) {
				g_variant_builder_add(&b, "{ss}", key, value);
			}
			lua_pop(L, 1);
		}
		lua_pop(L, 1);
	}
	return g_variant_builder_end(&b);
}

/* Sends the table at index to the tile: fields, with `tag` (taking
 * turns with other tags) and `badge` taken out of them */
static void tile_send(lua_State *L, const char *tile, int index) {
	char *badge = NULL;
	const char *tag = c8l_field_str(L, index, "tag", "");
	GVariant *fields = tile_fields(L, index, &badge);
	if (g_variant_n_children(fields) > 0) {
		c8_tiles_call("Update", g_variant_new("(ss@a{ss})", tile, tag,
			fields));
	} else {
		g_variant_unref(g_variant_ref_sink(fields));
	}
	if (badge) {
		c8_tiles_call("SetBadge", g_variant_new("(ss)", tile, badge));
		g_free(badge);
	}
}

/* c8.tile.update(id, fields) */
static int l_tile_update(lua_State *L) {
	const char *tile = luaL_checkstring(L, 1);
	luaL_checktype(L, 2, LUA_TTABLE);
	tile_send(L, tile, 2);
	return 0;
}

static int l_tile_badge(lua_State *L) {
	c8_tiles_call("SetBadge", g_variant_new("(ss)", luaL_checkstring(L, 1),
		luaL_optstring(L, 2, "")));
	return 0;
}

static int l_tile_clear(lua_State *L) {
	c8_tiles_call("Clear", g_variant_new("(s)", luaL_checkstring(L, 1)));
	return 0;
}

static int l_tile_remove(lua_State *L) {
	c8_tiles_call("Remove", g_variant_new("(ss)", luaL_checkstring(L, 1),
		luaL_checkstring(L, 2)));
	return 0;
}

/* A tile's provider: c8.provider{ tile, every, hidden_every, update }.
 * update(tile) runs at the start, every `every` seconds (`hidden_every`
 * while Start isn't showing, when given) and when a shell appears; what
 * it returns is sent: fields, or a list of them each with a tag. For an
 * answer that comes later it returns nothing and calls c8.tile.update. */

static struct {
	char *tile;
	int update; // ref
	double every, hidden_every;
	bool visible, started;
	guint timer;
	gint64 last; // monotonic us of the last update
	struct c8_tile_provider watch;
} prov = { .update = LUA_NOREF, .visible = true };

static void provider_arm(void);

static void provider_update(void) {
	lua_State *L = c8l;
	prov.last = g_get_monotonic_time();
	if (!c8l_push_ref(L, prov.update)) {
		return;
	}
	lua_pushstring(L, prov.tile);
	if (!c8l_call(L, 1, 1)) {
		return;
	}
	if (lua_istable(L, -1)) {
		if (lua_geti(L, -1, 1) == LUA_TTABLE) {
			/* Several, taking turns: each needs a tag */
			lua_pop(L, 1);
			lua_Integer n = luaL_len(L, -1);
			for (lua_Integer i = 1; i <= n; i++) {
				if (lua_geti(L, -1, i) == LUA_TTABLE) {
					if (c8l_field_str(L, -1, "tag", NULL) == NULL) {
						lua_pushinteger(L, i);
						lua_setfield(L, -2, "tag");
					}
					tile_send(L, prov.tile, -1);
				}
				lua_pop(L, 1);
			}
		} else {
			lua_pop(L, 1);
			tile_send(L, prov.tile, -1);
		}
	}
	lua_pop(L, 1);
}

static gboolean provider_tick(gpointer data) {
	prov.timer = 0;
	provider_update();
	provider_arm();
	return G_SOURCE_REMOVE;
}

static void provider_arm(void) {
	double s = prov.visible || prov.hidden_every <= 0 ? prov.every :
		prov.hidden_every;
	if (prov.timer) {
		g_source_remove(prov.timer);
	}
	prov.timer = g_timeout_add((guint)(MAX(s, 1) * 1000), provider_tick, NULL);
}

static void provider_quit(void *data) {
	exit(0);
}

static void provider_shell(void *data) {
	/* A new shell may have nothing of ours */
	provider_update();
	provider_arm();
}

static void provider_visible(bool visible, void *data) {
	if (visible == prov.visible) {
		return;
	}
	prov.visible = visible;
	if (visible && g_get_monotonic_time() - prov.last >
			(gint64)(prov.every * G_USEC_PER_SEC)) {
		provider_update();
	}
	provider_arm();
}

static int l_provider(lua_State *L) {
	luaL_checktype(L, 1, LUA_TTABLE);
	if (prov.started) {
		return luaL_error(L, "c8.provider was already called");
	}
	const char *tile = c8l_field_str(L, 1, "tile", NULL);
	if (tile == NULL) {
		return luaL_error(L, "c8.provider needs the tile's id (the shell "
			"gives it as the first argument: tile = c8.args[1])");
	}
	lua_getfield(L, 1, "update");
	if (!lua_isfunction(L, -1)) {
		return luaL_error(L, "c8.provider needs an update function");
	}
	prov.update = c8l_ref(L, -1);
	prov.tile = g_strdup(tile);
	prov.every = MAX(c8l_field_num(L, 1, "every", 60), 1);
	prov.hidden_every = c8l_field_num(L, 1, "hidden_every", 0);
	prov.started = true;
	prov.watch = (struct c8_tile_provider){
		.tile_id = prov.tile,
		.quit = provider_quit,
		.quit_unpinned = true,
		.shell = provider_shell,
		.visible = provider_visible,
		.wait_for_shell = true,
	};
	c8_tile_provider_watch(&prov.watch, NULL);
	provider_update();
	provider_arm();
	return 0;
}

bool c8l_provider_started(void) {
	return prov.started;
}

/* c8.notify{ title, body, icon, urgent }: a toast, in the app's colour.
 * A click opens the app (the shell does that for a toast with the app's
 * desktop entry and no default action). Sent and forgotten. */
static int l_notify(lua_State *L) {
	luaL_checktype(L, 1, LUA_TTABLE);
	const char *id = c8l_app ? c8ui_app_get_id(c8l_app) : NULL;
	GVariantBuilder hints;
	g_variant_builder_init(&hints, G_VARIANT_TYPE_VARDICT);
	if (id) {
		g_variant_builder_add(&hints, "{sv}", "desktop-entry",
			g_variant_new_string(id));
	}
	if (c8l_field_bool(L, 1, "urgent", false)) {
		g_variant_builder_add(&hints, "{sv}", "urgency",
			g_variant_new_byte(2));
	}
	const char *no_actions[] = { NULL };
	GVariant *params = g_variant_new("(susss^asa{sv}i)",
		c8l_field_str(L, 1, "app_name", id ? id : "c8-lua"), 0,
		c8l_field_str(L, 1, "icon", id ? id : ""),
		c8l_field_str(L, 1, "title", ""), c8l_field_str(L, 1, "body", ""),
		no_actions, &hints, -1);
	GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
	if (bus == NULL) {
		g_variant_unref(g_variant_ref_sink(params));
		return 0;
	}
	g_dbus_connection_call(bus, "org.freedesktop.Notifications",
		"/org/freedesktop/Notifications", "org.freedesktop.Notifications",
		"Notify", params, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
	g_object_unref(bus);
	return 0;
}

/* c8.now(): seconds on a clock that only goes forward, for stopwatches
 * (os.clock is CPU time, os.time whole seconds that can jump) */
static int l_now(lua_State *L) {
	lua_pushnumber(L, g_get_monotonic_time() / 1e6);
	return 1;
}

void c8l_sys_open(lua_State *L) {
	static const luaL_Reg fns[] = {
		{ "now", l_now },
		{ "notify", l_notify },
		{ "after", l_after },
		{ "every", l_every },
		{ "http", l_http },
		{ "run", l_run },
		{ "load", l_load },
		{ "save", l_save },
		{ "provider", l_provider },
		{ NULL, NULL },
	};
	luaL_setfuncs(L, fns, 0);

	lua_pushlightuserdata(L, null_mark);
	lua_setfield(L, -2, "null");

	lua_newtable(L);
	lua_pushcfunction(L, l_json_decode);
	lua_setfield(L, -2, "decode");
	lua_pushcfunction(L, l_json_encode);
	lua_setfield(L, -2, "encode");
	lua_setfield(L, -2, "json");

	lua_newtable(L);
	lua_pushcfunction(L, l_tile_update);
	lua_setfield(L, -2, "update");
	lua_pushcfunction(L, l_tile_badge);
	lua_setfield(L, -2, "badge");
	lua_pushcfunction(L, l_tile_clear);
	lua_setfield(L, -2, "clear");
	lua_pushcfunction(L, l_tile_remove);
	lua_setfield(L, -2, "remove");
	lua_setfield(L, -2, "tile");

	luaL_newmetatable(L, TIMER_META);
	lua_newtable(L);
	lua_pushcfunction(L, timer_cancel);
	lua_setfield(L, -2, "cancel");
	lua_setfield(L, -2, "__index");
	lua_pop(L, 1);
}
