/*
 * Open and save through org.freedesktop.portal.FileChooser. The call
 * returns a Request object; its Response signal brings the URIs. We
 * subscribe to the path the portal will use (from our handle_token)
 * before calling, so a fast answer isn't missed.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include "c8ui-files.h"
#include "wayland-private.h"

#define PORTAL "org.freedesktop.portal.Desktop"
#define PORTAL_PATH "/org/freedesktop/portal/desktop"
#define CHOOSER "org.freedesktop.portal.FileChooser"
#define REQUEST "org.freedesktop.portal.Request"

struct c8ui_file_dialog {
	GDBusConnection *bus;
	char *path; // the Request object
	guint signal;
	GCancellable *cancel; // the call itself
	c8ui_file_fn fn;
	void *data;
};

static void dialog_free(struct c8ui_file_dialog *d) {
	if (d->signal) {
		g_dbus_connection_signal_unsubscribe(d->bus, d->signal);
	}
	g_object_unref(d->cancel);
	g_object_unref(d->bus);
	g_free(d->path);
	free(d);
}

static void finish(struct c8ui_file_dialog *d, char **uris) {
	c8ui_file_fn fn = d->fn;
	void *data = d->data;
	dialog_free(d);
	fn(uris, data);
}

static void response(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data) {
	struct c8ui_file_dialog *d = data;
	guint32 code;
	GVariant *results;
	g_variant_get(params, "(u@a{sv})", &code, &results);
	char **uris = NULL;
	if (code == 0) {
		g_variant_lookup(results, "uris", "^as", &uris);
	}
	g_variant_unref(results);
	finish(d, code == 0 ? uris : NULL);
	g_strfreev(uris);
}

static void subscribe(struct c8ui_file_dialog *d, const char *path) {
	if (d->signal) {
		g_dbus_connection_signal_unsubscribe(d->bus, d->signal);
	}
	g_free(d->path);
	d->path = g_strdup(path);
	d->signal = g_dbus_connection_signal_subscribe(d->bus, PORTAL, REQUEST,
		"Response", path, NULL, G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE, response, d,
		NULL);
}

static void called(GObject *source, GAsyncResult *result, gpointer data) {
	GError *error = NULL;
	GVariant *reply = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source),
		result, &error);
	if (reply == NULL) {
		if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
			struct c8ui_file_dialog *d = data;
			fprintf(stderr, "c8ui: no file chooser: %s\n", error->message);
			finish(d, NULL);
		}
		g_error_free(error);
		return;
	}
	struct c8ui_file_dialog *d = data;
	const char *path;
	g_variant_get(reply, "(&o)", &path);
	/* Portals older than 0.9 picked a path of their own */
	if (strcmp(path, d->path) != 0) {
		subscribe(d, path);
	}
	g_variant_unref(reply);
}

static GVariant *filter_variant(const struct c8ui_file_filter *f) {
	GVariantBuilder rules;
	g_variant_builder_init(&rules, G_VARIANT_TYPE("a(us)"));
	const char *lists[] = { f->patterns, f->mime_types };
	for (guint32 kind = 0; kind < 2; kind++) { // 0 glob, 1 MIME type
		if (lists[kind] == NULL) {
			continue;
		}
		char **items = g_strsplit(lists[kind], ";", -1);
		for (char **i = items; *i; i++) {
			if (**i) {
				g_variant_builder_add(&rules, "(us)", kind, *i);
			}
		}
		g_strfreev(items);
	}
	return g_variant_new("(s@a(us))", f->name ? f->name : "",
		g_variant_builder_end(&rules));
}

static struct c8ui_file_dialog *ask(struct c8ui_window *parent,
		const char *method, const char *title,
		const struct c8ui_file_options *o, c8ui_file_fn fn, void *data) {
	GError *error = NULL;
	GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
	if (bus == NULL) {
		fprintf(stderr, "c8ui: no session bus: %s\n", error->message);
		g_error_free(error);
		return NULL;
	}
	static unsigned serial;
	char *handle_token = g_strdup_printf("c8ui%u_%u", (unsigned)getpid(),
		++serial);
	/* The request path is the sender's unique name, ':' left out and
	 * '.' made '_', then the token */
	char *sender = g_strdup(g_dbus_connection_get_unique_name(bus) + 1);
	for (char *p = sender; *p; p++) {
		if (*p == '.') {
			*p = '_';
		}
	}
	char *path = g_strdup_printf(PORTAL_PATH "/request/%s/%s", sender,
		handle_token);
	g_free(sender);

	struct c8ui_file_dialog *d = calloc(1, sizeof(*d));
	d->bus = bus;
	d->cancel = g_cancellable_new();
	d->fn = fn;
	d->data = data;
	subscribe(d, path);
	g_free(path);

	GVariantBuilder opts;
	g_variant_builder_init(&opts, G_VARIANT_TYPE_VARDICT);
	g_variant_builder_add(&opts, "{sv}", "handle_token",
		g_variant_new_take_string(handle_token));
	g_variant_builder_add(&opts, "{sv}", "modal", g_variant_new_boolean(TRUE));
	if (o->accept) {
		g_variant_builder_add(&opts, "{sv}", "accept_label",
			g_variant_new_string(o->accept));
	}
	if (o->multiple) {
		g_variant_builder_add(&opts, "{sv}", "multiple",
			g_variant_new_boolean(TRUE));
	}
	if (o->folder) {
		g_variant_builder_add(&opts, "{sv}", "directory",
			g_variant_new_boolean(TRUE));
	}
	if (o->filter_count > 0) {
		GVariantBuilder filters;
		g_variant_builder_init(&filters, G_VARIANT_TYPE("a(sa(us))"));
		for (int i = 0; i < o->filter_count; i++) {
			g_variant_builder_add_value(&filters, filter_variant(&o->filters[i]));
		}
		g_variant_builder_add(&opts, "{sv}", "filters",
			g_variant_builder_end(&filters));
		g_variant_builder_add(&opts, "{sv}", "current_filter",
			filter_variant(&o->filters[0]));
	}
	/* Paths are byte strings with their NUL */
	if (o->folder_path) {
		g_variant_builder_add(&opts, "{sv}", "current_folder",
			g_variant_new_bytestring(o->folder_path));
	}
	if (o->name) {
		g_variant_builder_add(&opts, "{sv}", "current_name",
			g_variant_new_string(o->name));
	}
	if (o->file) {
		g_variant_builder_add(&opts, "{sv}", "current_file",
			g_variant_new_bytestring(o->file));
	}

	const char *window = parent ? c8ui_window_export_handle(parent) : "";
	g_dbus_connection_call(bus, PORTAL, PORTAL_PATH, CHOOSER, method,
		g_variant_new("(ssa{sv})", window, o->title ? o->title : title, &opts),
		G_VARIANT_TYPE("(o)"), G_DBUS_CALL_FLAGS_NONE, G_MAXINT, d->cancel,
		called, d);
	return d;
}

struct c8ui_file_dialog *c8ui_file_open(struct c8ui_window *parent,
		const struct c8ui_file_options *options, c8ui_file_fn fn, void *data) {
	return ask(parent, "OpenFile",
		options->folder ? "Choose a folder" : "Open", options, fn, data);
}

struct c8ui_file_dialog *c8ui_file_save(struct c8ui_window *parent,
		const struct c8ui_file_options *options, c8ui_file_fn fn, void *data) {
	return ask(parent, "SaveFile", "Save", options, fn, data);
}

void c8ui_file_dialog_cancel(struct c8ui_file_dialog *d) {
	g_cancellable_cancel(d->cancel);
	g_dbus_connection_call(d->bus, PORTAL, d->path, REQUEST, "Close", NULL,
		NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
	dialog_free(d);
}
