/*
 * The file picker for every app: org.freedesktop.impl.portal.FileChooser
 * under org.freedesktop.impl.portal.desktop.c8, which xdg-desktop-portal
 * calls when cont8nuum-portals.conf names c8 for it (c8.portal says we
 * have it). Each call opens a picker window over the app that asked and
 * is answered when the user is done; the call's Request object (Close)
 * lets the portal take it back.
 *
 * Started for a call (D-Bus activation runs c8-files --portal), the app
 * stays a while after the last picker so the next one opens at once.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "files.h"

#define NAME "org.freedesktop.impl.portal.desktop.c8"
#define PATH "/org/freedesktop/portal/desktop"
#define LINGER_S 120

enum {
	RESPONSE_OK,
	RESPONSE_CANCELLED,
	RESPONSE_OTHER,
};

/* The three methods take and give the same */
#define CHOOSER_ARGS \
	"<arg type='o' name='handle' direction='in'/>" \
	"<arg type='s' name='app_id' direction='in'/>" \
	"<arg type='s' name='parent_window' direction='in'/>" \
	"<arg type='s' name='title' direction='in'/>" \
	"<arg type='a{sv}' name='options' direction='in'/>" \
	"<arg type='u' name='response' direction='out'/>" \
	"<arg type='a{sv}' name='results' direction='out'/>"

static const char chooser_xml[] =
	"<node><interface name='org.freedesktop.impl.portal.FileChooser'>"
	"<method name='OpenFile'>"
	CHOOSER_ARGS "</method>"
	"<method name='SaveFile'>"
	CHOOSER_ARGS "</method>"
	"<method name='SaveFiles'>"
	CHOOSER_ARGS "</method>"
	"</interface></node>";

static const char request_xml[] =
	"<node><interface name='org.freedesktop.impl.portal.Request'>"
	"<method name='Close'/></interface></node>";

struct request {
	GDBusMethodInvocation *inv;
	guint object;
	struct browser *browser;
	GPtrArray *names; // SaveFiles: the names to put in the folder
};

static struct {
	struct c8ui_app *app;
	GDBusConnection *bus;
	GDBusNodeInfo *chooser, *request;
	int active;
	guint linger;
	bool held;
} p;

/* Staying up */

static gboolean linger_over(gpointer data) {
	p.linger = 0;
	if (p.held && p.active == 0) {
		p.held = false;
		c8ui_app_release(p.app);
	}
	return G_SOURCE_REMOVE;
}

static void busy(void) {
	p.active++;
	if (!p.held) {
		p.held = true;
		c8ui_app_hold(p.app);
	}
	if (p.linger) {
		g_source_remove(p.linger);
		p.linger = 0;
	}
}

static void idle(void) {
	if (--p.active == 0 && p.held) {
		p.linger = g_timeout_add_seconds(LINGER_S, linger_over, NULL);
	}
}

void portal_expect(void) {
	busy();
	idle(); // lingers
}

/* Answers */

static void request_free(struct request *r) {
	if (r->object) {
		g_dbus_connection_unregister_object(p.bus, r->object);
	}
	if (r->names) {
		g_ptr_array_unref(r->names);
	}
	free(r);
	idle();
}

static void reply(struct request *r, guint32 response, GVariantBuilder *res) {
	GVariantBuilder empty;
	if (res == NULL) {
		g_variant_builder_init(&empty, G_VARIANT_TYPE_VARDICT);
		res = &empty;
	}
	g_dbus_method_invocation_return_value(r->inv,
		g_variant_new("(ua{sv})", response, res));
	r->inv = NULL;
}

static void picked(struct browser *b, char **uris, void *data) {
	struct request *r = data;
	if (r->inv == NULL) {
		request_free(r); // closed by the portal: already answered
		return;
	}
	if (uris == NULL) {
		reply(r, RESPONSE_CANCELLED, NULL);
		request_free(r);
		return;
	}
	GVariantBuilder res;
	g_variant_builder_init(&res, G_VARIANT_TYPE_VARDICT);
	GVariantBuilder list;
	g_variant_builder_init(&list, G_VARIANT_TYPE_STRING_ARRAY);
	if (r->names) {
		/* SaveFiles: the folder chosen, each name in it */
		GFile *dir = g_file_new_for_uri(uris[0]);
		for (guint i = 0; i < r->names->len; i++) {
			/* Never over a file that's there: the names weren't the
			 * user's, so one taken becomes "name (2)" */
			GFile *f = files_unique_child(dir, r->names->pdata[i]);
			char *uri = g_file_get_uri(f);
			g_variant_builder_add(&list, "s", uri);
			g_free(uri);
			g_object_unref(f);
		}
		g_object_unref(dir);
	} else {
		for (int i = 0; uris[i]; i++) {
			g_variant_builder_add(&list, "s", uris[i]);
		}
	}
	g_variant_builder_add(&res, "{sv}", "uris", g_variant_builder_end(&list));
	g_variant_builder_add(&res, "{sv}", "writable", g_variant_new_boolean(TRUE));
	reply(r, RESPONSE_OK, &res);
	request_free(r);
}

static void request_call(GDBusConnection *conn, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *inv, gpointer data) {
	struct request *r = data;
	/* Close: the app gave up. No answer to the call beyond "other". */
	g_dbus_method_invocation_return_value(inv, NULL);
	if (r->inv) {
		reply(r, RESPONSE_OTHER, NULL);
	}
	browser_close(r->browser); // picked() frees r once it goes
}

static const GDBusInterfaceVTable request_vtable = {
	.method_call = request_call,
};

/* Reading the options */

static struct pick_filter *read_filter(GVariant *v) {
	const char *name;
	GVariantIter *rules;
	g_variant_get(v, "(&sa(us))", &name, &rules);
	struct pick_filter *f = calloc(1, sizeof(*f));
	f->name = g_strdup(name);
	f->globs = g_ptr_array_new_with_free_func(g_free);
	f->mimes = g_ptr_array_new_with_free_func(g_free);
	guint32 kind;
	const char *rule;
	while (g_variant_iter_next(rules, "(u&s)", &kind, &rule)) {
		if (kind == 0) {
			g_ptr_array_add(f->globs, g_strdup(rule));
		} else {
			g_ptr_array_add(f->mimes, g_strdup(rule));
		}
	}
	g_variant_iter_free(rules);
	return f;
}

static GFile *path_option(GVariant *options, const char *key) {
	const char *path = NULL;
	if (g_variant_lookup(options, key, "^&ay", &path) && path && path[0]) {
		return g_file_new_for_path(path);
	}
	return NULL;
}

static void chooser_call(GDBusConnection *conn, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *inv, gpointer data) {
	const char *handle, *app_id, *parent, *title;
	GVariant *options;
	g_variant_get(params, "(&o&s&s&s@a{sv})", &handle, &app_id, &parent,
		&title, &options);
	bool save = strcmp(method, "SaveFile") == 0;
	bool save_files = strcmp(method, "SaveFiles") == 0;

	struct request *r = calloc(1, sizeof(*r));
	r->inv = inv;
	busy();
	struct pick_options o = {
		.mode = save ? MODE_SAVE : MODE_OPEN,
		.title = title && title[0] ? title : NULL,
		.parent = parent && parent[0] ? parent : NULL,
		.done = picked,
		.data = r,
	};
	char *save_title = NULL;
	g_variant_lookup(options, "accept_label", "&s", &o.accept);
	gboolean b;
	if (g_variant_lookup(options, "multiple", "b", &b)) {
		o.multiple = b;
	}
	if (g_variant_lookup(options, "directory", "b", &b)) {
		o.folders = b;
	}
	if (save_files) {
		/* Where to put several files: a folder is chosen */
		o.folders = true;
		r->names = g_ptr_array_new_with_free_func(g_free);
		GVariantIter *files;
		if (g_variant_lookup(options, "files", "aay", &files)) {
			const char *name;
			while (g_variant_iter_next(files, "^&ay", &name)) {
				/* A plain name, in the folder chosen and nowhere else,
				 * and not a hidden one: the app asking picks these, and
				 * ".bashrc" in the home folder isn't a document */
				if (name[0] && name[0] != '.' && !strchr(name, '/') &&
						g_utf8_validate(name, -1, NULL)) {
					g_ptr_array_add(r->names, g_strdup(name));
				}
			}
			g_variant_iter_free(files);
		}
		if (r->names->len == 0) {
			g_variant_unref(options);
			reply(r, RESPONSE_OTHER, NULL);
			request_free(r);
			return;
		}
		/* The title says what goes into the folder chosen */
		GString *what = g_string_new("Save ");
		guint shown = MIN(r->names->len, 3);
		for (guint i = 0; i < shown; i++) {
			g_string_append_printf(what, "%s%.60s", i ? ", " : "",
				(char *)r->names->pdata[i]);
		}
		if (r->names->len > shown) {
			g_string_append_printf(what, " and %u more",
				r->names->len - shown);
		}
		g_string_append(what, " here");
		save_title = g_string_free(what, FALSE);
		o.title = save_title;
	}
	GVariant *filters = g_variant_lookup_value(options, "filters",
		G_VARIANT_TYPE("a(sa(us))"));
	if (filters && !o.folders) {
		o.filters = g_ptr_array_new_with_free_func(pick_filter_free);
		GVariantIter iter;
		g_variant_iter_init(&iter, filters);
		GVariant *f;
		while ((f = g_variant_iter_next_value(&iter))) {
			g_ptr_array_add(o.filters, read_filter(f));
			g_variant_unref(f);
		}
	}
	GVariant *current = g_variant_lookup_value(options, "current_filter",
		G_VARIANT_TYPE("(sa(us))"));
	if (current && !o.folders) {
		const char *name;
		g_variant_get(current, "(&s@a(us))", &name, NULL);
		if (o.filters == NULL) {
			o.filters = g_ptr_array_new_with_free_func(pick_filter_free);
		}
		o.filter = -1;
		for (guint i = 0; i < o.filters->len; i++) {
			if (strcmp(((struct pick_filter *)o.filters->pdata[i])->name,
					name) == 0) {
				o.filter = i;
			}
		}
		if (o.filter < 0) {
			/* Not among them: it comes first */
			g_ptr_array_insert(o.filters, 0, read_filter(current));
			o.filter = 0;
		}
	}
	o.folder = path_option(options, "current_folder");
	GFile *file = save ? path_option(options, "current_file") : NULL;
	char *name = NULL;
	if (file && o.folder == NULL) {
		o.folder = g_file_get_parent(file);
	}
	if (file) {
		name = g_file_get_basename(file);
	}
	const char *current_name = NULL;
	if (save && g_variant_lookup(options, "current_name", "&s",
			&current_name)) {
		o.name = current_name;
	} else {
		o.name = name;
	}

	r->browser = browser_new_picker(&o);
	GError *error = NULL;
	r->object = g_dbus_connection_register_object(p.bus, handle,
		p.request->interfaces[0], &request_vtable, r, NULL, &error);
	if (r->object == 0) {
		fprintf(stderr, "c8-files: request %s: %s\n", handle, error->message);
		g_error_free(error);
	}
	browser_present(r->browser);

	g_free(save_title);
	g_free(name);
	g_clear_object(&file);
	g_clear_object(&o.folder);
	if (current) {
		g_variant_unref(current);
	}
	if (filters) {
		g_variant_unref(filters);
	}
	g_variant_unref(options);
}

static const GDBusInterfaceVTable chooser_vtable = {
	.method_call = chooser_call,
};

static void name_lost(GDBusConnection *conn, const char *name, gpointer data) {
	/* Another backend has it, or the bus went: the app is just Files */
}

void portal_init(struct c8ui_app *app) {
	p.app = app;
	GError *error = NULL;
	p.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
	if (p.bus == NULL) {
		fprintf(stderr, "c8-files: no session bus: %s\n", error->message);
		g_error_free(error);
		return;
	}
	p.chooser = g_dbus_node_info_new_for_xml(chooser_xml, NULL);
	p.request = g_dbus_node_info_new_for_xml(request_xml, NULL);
	if (g_dbus_connection_register_object(p.bus, PATH,
			p.chooser->interfaces[0], &chooser_vtable, NULL, NULL,
			&error) == 0) {
		fprintf(stderr, "c8-files: no portal: %s\n", error->message);
		g_error_free(error);
		return;
	}
	g_bus_own_name_on_connection(p.bus, NAME, G_BUS_NAME_OWNER_FLAGS_NONE,
		NULL, name_lost, NULL, NULL);
}
