/*
 * c8-lua SCRIPT [FILE...]: runs a c8ui app or a live tile provider
 * written in Lua. The script is run once, top to bottom; what it is, it
 * says by calling c8.app{...} (an app: one copy runs, files handed over,
 * charms) or c8.provider{...} (a tile kept fresh without a window).
 */
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <lualib.h>
#include <c8ui/c8ui-charms.h>
#include "c8lua.h"

lua_State *c8l;
struct c8ui_app *c8l_app;

static struct {
	char *id;
	int startup, open, shutdown; // refs
	int search, result; // the Search charm
	int settings; // the Settings charm: the list given
	int wake; // a wake booked with c8.wake is due
	struct c8ui_charms *charms;
	bool declared;
} app = { .startup = LUA_NOREF, .open = LUA_NOREF, .shutdown = LUA_NOREF,
	.search = LUA_NOREF, .result = LUA_NOREF, .settings = LUA_NOREF,
	.wake = LUA_NOREF };

/* Calling into Lua */

static int traceback(lua_State *L) {
	const char *msg = lua_tostring(L, 1);
	luaL_traceback(L, L, msg ? msg : "(an error that isn't text)", 1);
	return 1;
}

bool c8l_call(lua_State *L, int nargs, int nresults) {
	int base = lua_gettop(L) - nargs;
	lua_pushcfunction(L, traceback);
	lua_insert(L, base);
	int status = lua_pcall(L, nargs, nresults, base);
	lua_remove(L, base);
	if (status != LUA_OK) {
		fprintf(stderr, "c8-lua: %s\n", lua_tostring(L, -1));
		lua_pop(L, 1);
		return false;
	}
	return true;
}

int c8l_ref(lua_State *L, int index) {
	if (!lua_isfunction(L, index)) {
		return LUA_NOREF;
	}
	lua_pushvalue(L, index);
	return luaL_ref(L, LUA_REGISTRYINDEX);
}

void c8l_unref(lua_State *L, int ref) {
	luaL_unref(L, LUA_REGISTRYINDEX, ref);
}

bool c8l_push_ref(lua_State *L, int ref) {
	if (ref == LUA_NOREF || ref == LUA_REFNIL) {
		return false;
	}
	lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
	return true;
}

/* Reading arguments */

uint32_t c8l_color(lua_State *L, int index, uint32_t fallback) {
	uint32_t rgb;
	if (lua_type(L, index) == LUA_TNUMBER) {
		return (uint32_t)lua_tointeger(L, index) & 0xffffff;
	}
	if (lua_type(L, index) == LUA_TSTRING &&
			c8ui_parse_color(lua_tostring(L, index), &rgb)) {
		return rgb;
	}
	return fallback;
}

const char *c8l_field_str(lua_State *L, int index, const char *key,
		const char *fallback) {
	lua_getfield(L, index, key);
	/* Still held by the table, so good after the pop */
	const char *s = lua_type(L, -1) == LUA_TSTRING ? lua_tostring(L, -1) :
		fallback;
	lua_pop(L, 1);
	return s;
}

double c8l_field_num(lua_State *L, int index, const char *key,
		double fallback) {
	lua_getfield(L, index, key);
	double n = lua_isnumber(L, -1) ? lua_tonumber(L, -1) : fallback;
	lua_pop(L, 1);
	return n;
}

bool c8l_field_bool(lua_State *L, int index, const char *key, bool fallback) {
	lua_getfield(L, index, key);
	bool b = lua_isnil(L, -1) ? fallback : lua_toboolean(L, -1);
	lua_pop(L, 1);
	return b;
}

char **c8l_strings(lua_State *L, int index, const char *key, int *count) {
	GPtrArray *a = g_ptr_array_new();
	index = lua_absindex(L, index);
	if (key) {
		lua_getfield(L, index, key);
	} else {
		lua_pushvalue(L, index);
	}
	if (lua_istable(L, -1)) {
		lua_Integer n = luaL_len(L, -1);
		for (lua_Integer i = 1; i <= n; i++) {
			lua_geti(L, -1, i);
			const char *s = luaL_tolstring(L, -1, NULL);
			g_ptr_array_add(a, g_strdup(s));
			lua_pop(L, 2);
		}
	}
	lua_pop(L, 1);
	if (count) {
		*count = a->len;
	}
	g_ptr_array_add(a, NULL);
	return (char **)g_ptr_array_free(a, FALSE);
}

/* The Search charm: search(query) returns a list of { id, title,
 * subtitle, icon }, result(id, query) opens one */

static void charm_search(struct c8ui_search *s, const char *query,
		void *data) {
	lua_State *L = c8l;
	if (!c8l_push_ref(L, app.search)) {
		return;
	}
	lua_pushstring(L, query);
	if (!c8l_call(L, 1, 1)) {
		return;
	}
	if (lua_istable(L, -1)) {
		lua_Integer n = luaL_len(L, -1);
		for (lua_Integer i = 1; i <= n; i++) {
			lua_geti(L, -1, i);
			if (lua_istable(L, -1)) {
				const char *title = c8l_field_str(L, -1, "title", "");
				c8ui_search_add(s, c8l_field_str(L, -1, "id", title), title,
					c8l_field_str(L, -1, "subtitle", NULL),
					c8l_field_str(L, -1, "icon", NULL));
			}
			lua_pop(L, 1);
		}
	}
	lua_pop(L, 1);
}

static void charm_result(const char *id, const char *query, void *data) {
	lua_State *L = c8l;
	if (c8l_push_ref(L, app.result)) {
		lua_pushstring(L, id);
		lua_pushstring(L, query);
		c8l_call(L, 2, 0);
	}
}

/* The Settings charm. settings = { { id, label, build = fn(page) } or
 * { id, label, action = fn } }; a page's controls are added through the
 * page object, their change functions kept by "PAGE/SETTING" until the
 * page is built again. */

#define PAGE_META "c8.settings_page"
#define CHANGES "c8.setting_changes"

struct page {
	struct c8ui_settings_page *page; // NULL once the build is over
	const char *id;
};

/* Pushes settings[i] for the entry whose id is `id` */
static bool push_settings_entry(lua_State *L, const char *id) {
	if (!c8l_push_ref(L, app.settings)) {
		return false;
	}
	lua_Integer n = luaL_len(L, -1);
	for (lua_Integer i = 1; i <= n; i++) {
		lua_geti(L, -1, i);
		if (lua_istable(L, -1) &&
				g_strcmp0(c8l_field_str(L, -1, "id", NULL), id) == 0) {
			lua_remove(L, -2);
			return true;
		}
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
	return false;
}

static void setting_changed(struct c8ui_setting *s, void *data) {
	lua_State *L = c8l;
	char *key = g_strdup_printf("%s/%s", (const char *)data, c8ui_setting_id(s));
	lua_getfield(L, LUA_REGISTRYINDEX, CHANGES);
	lua_getfield(L, -1, key);
	g_free(key);
	if (!lua_istable(L, -1)) {
		lua_pop(L, 2);
		return;
	}
	lua_getfield(L, -1, "fn");
	lua_getfield(L, -2, "kind");
	const char *kind = lua_tostring(L, -1);
	lua_pop(L, 1);
	if (g_strcmp0(kind, "toggle") == 0) {
		lua_pushboolean(L, c8ui_setting_get_bool(s));
	} else if (g_strcmp0(kind, "choice") == 0) {
		lua_pushinteger(L, c8ui_setting_get_int(s) + 1);
	} else if (g_strcmp0(kind, "slider") == 0) {
		lua_pushnumber(L, c8ui_setting_get_double(s));
	} else if (g_strcmp0(kind, "text") == 0) {
		lua_pushstring(L, c8ui_setting_get_text(s));
	} else {
		lua_pushnil(L);
	}
	if (lua_isfunction(L, -2)) {
		c8l_call(L, 1, 0);
	} else {
		lua_pop(L, 2);
	}
	lua_pop(L, 2);
}

/* page:toggle{...} and the rest: one function, told apart by upvalue */
static int page_add(lua_State *L) {
	struct page *p = luaL_checkudata(L, 1, PAGE_META);
	const char *kind = lua_tostring(L, lua_upvalueindex(1));
	if (p->page == NULL) {
		return luaL_error(L, "a settings page can only be filled while it "
			"is being built");
	}
	if (strcmp(kind, "heading") == 0 || strcmp(kind, "paragraph") == 0) {
		const char *text = lua_istable(L, 2) ?
			c8l_field_str(L, 2, "text", "") : luaL_checkstring(L, 2);
		if (kind[0] == 'h') {
			c8ui_page_heading(p->page, text);
		} else {
			c8ui_page_paragraph(p->page, text);
		}
		return 0;
	}
	luaL_checktype(L, 2, LUA_TTABLE);
	const char *id = c8l_field_str(L, 2, "id", NULL);
	const char *label = c8l_field_str(L, 2, "label", "");
	if (id == NULL) {
		return luaL_error(L, "a setting needs an id");
	}
	void *data = (void *)p->id;
	struct c8ui_setting *s = NULL;
	if (strcmp(kind, "toggle") == 0) {
		s = c8ui_page_toggle(p->page, id, label,
			c8l_field_bool(L, 2, "on", false), setting_changed, data);
	} else if (strcmp(kind, "choice") == 0) {
		int count;
		char **items = c8l_strings(L, 2, "items", &count);
		int selected = (int)c8l_field_num(L, 2, "selected", 1) - 1;
		if (c8l_field_bool(L, 2, "buttons", false)) {
			s = c8ui_page_buttons(p->page, id, label,
				(const char *const *)items, count, selected,
				setting_changed, data);
		} else {
			s = c8ui_page_choice(p->page, id, label,
				(const char *const *)items, count, selected,
				setting_changed, data);
		}
		g_strfreev(items);
	} else if (strcmp(kind, "slider") == 0) {
		s = c8ui_page_slider(p->page, id, label,
			c8l_field_num(L, 2, "min", 0), c8l_field_num(L, 2, "max", 100),
			c8l_field_num(L, 2, "step", 1), c8l_field_num(L, 2, "value", 0),
			setting_changed, data);
	} else if (strcmp(kind, "text") == 0) {
		s = c8ui_page_text(p->page, id, label,
			c8l_field_str(L, 2, "text", ""), setting_changed, data);
		const char *hint = c8l_field_str(L, 2, "placeholder", NULL);
		if (hint) {
			c8ui_setting_set_placeholder(s, hint);
		}
		if (c8l_field_bool(L, 2, "password", false)) {
			c8ui_setting_set_password(s, true);
		}
	} else if (strcmp(kind, "button") == 0) {
		s = c8ui_page_button(p->page, id, label, setting_changed, data);
	} else {
		s = c8ui_page_link(p->page, id, label, setting_changed, data);
	}
	const char *description = c8l_field_str(L, 2, "description", NULL);
	if (description) {
		c8ui_setting_set_description(s, description);
	}
	if (!c8l_field_bool(L, 2, "enabled", true)) {
		c8ui_setting_set_enabled(s, false);
	}
	/* What runs when it changes, and how to read the value */
	char *key = g_strdup_printf("%s/%s", p->id, id);
	lua_getfield(L, LUA_REGISTRYINDEX, CHANGES);
	lua_createtable(L, 0, 2);
	lua_pushstring(L, kind);
	lua_setfield(L, -2, "kind");
	lua_getfield(L, 2, "on_change");
	if (lua_isnil(L, -1)) {
		lua_pop(L, 1);
		lua_getfield(L, 2, "on_click");
	}
	lua_setfield(L, -2, "fn");
	lua_setfield(L, -2, key);
	lua_pop(L, 1);
	g_free(key);
	return 0;
}

static void settings_build(struct c8ui_settings_page *page, void *data) {
	lua_State *L = c8l;
	if (!push_settings_entry(L, data)) {
		return;
	}
	lua_getfield(L, -1, "build");
	lua_remove(L, -2);
	if (!lua_isfunction(L, -1)) {
		lua_pop(L, 1);
		return;
	}
	struct page *p = lua_newuserdatauv(L, sizeof(*p), 0);
	p->page = page;
	p->id = data;
	luaL_setmetatable(L, PAGE_META);
	lua_pushvalue(L, -1);
	int keep = luaL_ref(L, LUA_REGISTRYINDEX);
	c8l_call(L, 1, 0);
	p->page = NULL;
	luaL_unref(L, LUA_REGISTRYINDEX, keep);
}

static void settings_action(void *data) {
	lua_State *L = c8l;
	if (!push_settings_entry(L, data)) {
		return;
	}
	lua_getfield(L, -1, "action");
	lua_remove(L, -2);
	if (lua_isfunction(L, -1)) {
		c8l_call(L, 0, 0);
	} else {
		lua_pop(L, 1);
	}
}

static void charms_start(lua_State *L) {
	if (app.search == LUA_NOREF && app.settings == LUA_NOREF) {
		return;
	}
	app.charms = c8ui_charms_new(c8l_app);
	if (app.charms == NULL) {
		return;
	}
	if (app.search != LUA_NOREF) {
		c8ui_charms_on_search(app.charms, charm_search, charm_result, NULL,
			NULL);
	}
	if (!c8l_push_ref(L, app.settings)) {
		return;
	}
	lua_Integer n = luaL_len(L, -1);
	for (lua_Integer i = 1; i <= n; i++) {
		lua_geti(L, -1, i);
		if (lua_istable(L, -1)) {
			const char *id = c8l_field_str(L, -1, "id", NULL);
			const char *label = c8l_field_str(L, -1, "label", id);
			lua_getfield(L, -1, "build");
			bool page = lua_isfunction(L, -1);
			lua_pop(L, 1);
			if (id && page) {
				c8ui_charms_add_page(app.charms, id, label, settings_build,
					(void *)g_intern_string(id));
			} else if (id) {
				c8ui_charms_add_action(app.charms, id, label,
					settings_action, (void *)g_intern_string(id));
			}
		}
		lua_pop(L, 1);
	}
	lua_pop(L, 1);
}

/* c8.settings_changed([page]): a page shows something else now */
static int l_settings_changed(lua_State *L) {
	if (app.charms) {
		c8ui_charms_changed(app.charms, luaL_optstring(L, 1, NULL));
	}
	return 0;
}

/* The app */

static void app_startup(struct c8ui_app *a, void *data) {
	lua_State *L = c8l;
	c8l_app = a;
	charms_start(L);
	if (c8l_push_ref(L, app.startup)) {
		c8l_call(L, 0, 0);
	}
}

static void app_open(struct c8ui_app *a, char **uris, void *data) {
	lua_State *L = c8l;
	if (!c8l_push_ref(L, app.open)) {
		return;
	}
	lua_newtable(L);
	for (int i = 0; uris && uris[i]; i++) {
		lua_pushstring(L, uris[i]);
		lua_seti(L, -2, i + 1);
	}
	c8l_call(L, 1, 0);
}

static void app_shutdown(struct c8ui_app *a, void *data) {
	lua_State *L = c8l;
	if (c8l_push_ref(L, app.shutdown)) {
		c8l_call(L, 0, 0);
	}
	if (app.charms) {
		c8ui_charms_destroy(app.charms);
		app.charms = NULL;
	}
}

/* wake(tag, due): done when it returns, unless it returns true, when
 * c8.wake.done() says so (or the time is up) */
static void app_wake(struct c8ui_app *a, const char *tag, int64_t due,
		void *data) {
	lua_State *L = c8l;
	bool later = false;
	if (c8l_push_ref(L, app.wake)) {
		lua_pushstring(L, tag);
		lua_pushinteger(L, due);
		if (c8l_call(L, 2, 1)) {
			later = lua_toboolean(L, -1);
			lua_pop(L, 1);
		}
	}
	if (!later) {
		c8ui_app_wake_done(a);
	}
}

/* c8.wake.at(tag, when [, every]): when in os.time() seconds */
static int l_wake_at(lua_State *L) {
	const char *tag = luaL_checkstring(L, 1);
	lua_Integer when = luaL_checkinteger(L, 2);
	lua_Integer every = luaL_optinteger(L, 3, 0);
	if (c8l_app == NULL) {
		return luaL_error(L, "c8.wake is for an app's functions (open, "
			"wake, a button...), not the script's first run");
	}
	if (every != 0 && every < 60) {
		return luaL_error(L, "a wake repeats at least 60 seconds apart");
	}
	c8ui_app_wake_at(c8l_app, tag, when, (unsigned)every);
	return 0;
}

/* c8.wake.every(tag, seconds [, first]) */
static int l_wake_every(lua_State *L) {
	lua_Integer every = luaL_checkinteger(L, 2);
	lua_Integer first = luaL_optinteger(L, 3, (lua_Integer)time(NULL) + every);
	lua_settop(L, 1);
	lua_pushinteger(L, first);
	lua_pushinteger(L, every);
	return l_wake_at(L);
}

static int l_wake_cancel(lua_State *L) {
	const char *tag = luaL_checkstring(L, 1);
	if (c8l_app) {
		c8ui_app_wake_cancel(c8l_app, tag);
	}
	return 0;
}

static int l_wake_done(lua_State *L) {
	if (c8l_app) {
		c8ui_app_wake_done(c8l_app);
	}
	return 0;
}

/* c8.app{ id, startup, open, shutdown, search, result, settings, wake } */
static int l_app(lua_State *L) {
	luaL_checktype(L, 1, LUA_TTABLE);
	if (app.declared) {
		return luaL_error(L, "c8.app was already called");
	}
	const char *id = c8l_field_str(L, 1, "id", NULL);
	if (id == NULL || strchr(id, '.') == NULL) {
		return luaL_error(L, "c8.app needs an id like \"org.example.Notes\"");
	}
	app.id = g_strdup(id);
	lua_getfield(L, 1, "open");
	if (!lua_isfunction(L, -1)) {
		return luaL_error(L, "c8.app needs an open function");
	}
	app.open = c8l_ref(L, -1);
	lua_getfield(L, 1, "startup");
	app.startup = c8l_ref(L, -1);
	lua_getfield(L, 1, "shutdown");
	app.shutdown = c8l_ref(L, -1);
	lua_getfield(L, 1, "search");
	app.search = c8l_ref(L, -1);
	lua_getfield(L, 1, "result");
	app.result = c8l_ref(L, -1);
	lua_getfield(L, 1, "wake");
	app.wake = c8l_ref(L, -1);
	lua_getfield(L, 1, "settings");
	if (lua_istable(L, -1)) {
		app.settings = luaL_ref(L, LUA_REGISTRYINDEX);
	}
	app.declared = true;
	return 0;
}

static int l_quit(lua_State *L) {
	if (c8l_app) {
		c8ui_app_quit(c8l_app, (int)luaL_optinteger(L, 1, 0));
	} else {
		exit((int)luaL_optinteger(L, 1, 0));
	}
	return 0;
}

static const luaL_Reg app_fns[] = {
	{ "app", l_app },
	{ "quit", l_quit },
	{ "settings_changed", l_settings_changed },
	{ NULL, NULL },
};

static const luaL_Reg wake_fns[] = {
	{ "at", l_wake_at },
	{ "every", l_wake_every },
	{ "cancel", l_wake_cancel },
	{ "done", l_wake_done },
	{ NULL, NULL },
};

static int open_c8(lua_State *L) {
	luaL_newlib(L, app_fns);
	luaL_newlib(L, wake_fns);
	lua_setfield(L, -2, "wake");
	c8l_ui_open(L);
	c8l_draw_open(L);
	c8l_sys_open(L);
	return 1;
}

static void page_meta(lua_State *L) {
	static const char *const kinds[] = { "toggle", "choice", "slider",
		"text", "button", "link", "heading", "paragraph" };
	luaL_newmetatable(L, PAGE_META);
	lua_newtable(L);
	for (size_t i = 0; i < G_N_ELEMENTS(kinds); i++) {
		lua_pushstring(L, kinds[i]);
		lua_pushcclosure(L, page_add, 1);
		lua_setfield(L, -2, kinds[i]);
	}
	lua_setfield(L, -2, "__index");
	lua_pop(L, 1);
	lua_newtable(L);
	lua_setfield(L, LUA_REGISTRYINDEX, CHANGES);
}

int main(int argc, char **argv) {
	if (argc < 2 || argv[1][0] == '-') {
		fprintf(stderr, "Usage: c8-lua SCRIPT [FILE...]\n"
			"\n"
			"Runs a cont8nuum app or live tile provider written in Lua.\n");
		return argc < 2 ? 2 : strcmp(argv[1], "--help") != 0 ? 2 : 0;
	}
	setlocale(LC_ALL, "");
	/* Lua reads and writes numbers by the C locale's rules */
	setlocale(LC_NUMERIC, "C");

	lua_State *L = c8l = luaL_newstate();
	luaL_openlibs(L);
	luaL_requiref(L, "c8", open_c8, 1);
	page_meta(L);

	/* c8.dir: where the script is, for what it ships beside itself;
	 * require looks there too */
	char *path = g_canonicalize_filename(argv[1], NULL);
	char *dir = g_path_get_dirname(path);
	lua_pushstring(L, dir);
	lua_setfield(L, -2, "dir");
	lua_newtable(L);
	for (int i = 2, n = 1; i < argc; i++) {
		/* A wake's arguments are c8ui's (the app's wake gets them) */
		if (strcmp(argv[i], "--c8-wake") == 0) {
			i += 2;
			continue;
		}
		lua_pushstring(L, argv[i]);
		lua_seti(L, -2, n++);
	}
	lua_setfield(L, -2, "args");
	lua_pop(L, 1);
	lua_getglobal(L, "package");
	lua_getfield(L, -1, "path");
	char *search = g_strdup_printf("%s/?.lua;%s/?/init.lua;%s", dir, dir,
		lua_tostring(L, -1));
	lua_pop(L, 1);
	lua_pushstring(L, search);
	lua_setfield(L, -2, "path");
	lua_pop(L, 1);
	g_free(search);
	g_free(dir);

	if (luaL_loadfile(L, path) != LUA_OK) {
		fprintf(stderr, "c8-lua: %s\n", lua_tostring(L, -1));
		return 1;
	}
	if (!c8l_call(L, 0, 0)) {
		return 1;
	}

	/* The process ends without closing the state: widgets outlive
	 * anything we could close it before */
	if (app.declared) {
		/* A wake starts this runner with this script */
		char *self = g_file_read_link("/proc/self/exe", NULL);
		const char *command[] = { self ? self : "c8-lua", path, NULL };
		struct c8ui_app_info info = {
			.id = app.id,
			.startup = app_startup,
			.open = app_open,
			.shutdown = app_shutdown,
			.wake = app_wake,
			.command = command,
		};
		argv[1] = argv[0];
		return c8ui_app_main(&info, argc - 1, argv + 1);
	}
	if (c8l_provider_started()) {
		GMainLoop *loop = g_main_loop_new(NULL, FALSE);
		g_main_loop_run(loop);
		return 0;
	}
	/* Neither: a plain script that has run */
	return 0;
}
