/*
 * org.freedesktop.FileManager1: how other apps ask the file manager to
 * show something. Browsers call ShowItems for "Open containing folder"
 * (LibreWolf, Firefox, Chromium), and only open the folder, with nothing
 * selected, when nobody serves it. D-Bus starts c8-files --portal for a
 * call when Files isn't running.
 *
 * ShowItems opens a window per folder with its items selected,
 * ShowFolders a window on each folder; ShowItemProperties is treated as
 * ShowItems (the Properties flyout needs a place on screen to hang
 * from). The startup id is the caller's activation token.
 */
#include <stdio.h>
#include "files.h"

#define NAME "org.freedesktop.FileManager1"
#define PATH "/org/freedesktop/FileManager1"

static const char fm_xml[] =
	"<node>"
	" <interface name='org.freedesktop.FileManager1'>"
	"  <method name='ShowFolders'>"
	"   <arg type='as' name='URIs' direction='in'/>"
	"   <arg type='s' name='StartupId' direction='in'/>"
	"  </method>"
	"  <method name='ShowItems'>"
	"   <arg type='as' name='URIs' direction='in'/>"
	"   <arg type='s' name='StartupId' direction='in'/>"
	"  </method>"
	"  <method name='ShowItemProperties'>"
	"   <arg type='as' name='URIs' direction='in'/>"
	"   <arg type='s' name='StartupId' direction='in'/>"
	"  </method>"
	" </interface>"
	"</node>";

static struct c8ui_app *fm_app;

/* Some callers send paths, not URIs */
static GFile *file_from(const char *s) {
	return g_file_new_for_commandline_arg(s);
}

/* Anything on the bus can ask, so only what's here already: showing a
 * server not connected to connects to it, which tells that server who
 * we are and may ask for a password, and that is for the user to start */
static bool here_already(GFile *file) {
	if (g_file_is_native(file) || g_file_has_uri_scheme(file, "trash") ||
			g_file_has_uri_scheme(file, "recent")) {
		return true;
	}
	GMount *mount = g_file_find_enclosing_mount(file, NULL, NULL);
	if (mount == NULL) {
		return false;
	}
	g_object_unref(mount);
	return true;
}

static void show_folders(const char **uris) {
	for (int i = 0; uris[i]; i++) {
		GFile *dir = file_from(uris[i]);
		if (here_already(dir)) {
			browser_present(browser_new(dir));
		}
		g_object_unref(dir);
	}
}

/* One window per folder, with every item asked for there selected */
static void show_items(const char **uris) {
	GHashTable *windows = g_hash_table_new_full(g_file_hash,
		(GEqualFunc)g_file_equal, g_object_unref, NULL);
	GPtrArray *order = g_ptr_array_new();
	for (int i = 0; uris[i]; i++) {
		GFile *file = file_from(uris[i]);
		if (!here_already(file)) {
			g_object_unref(file);
			continue;
		}
		GFile *parent = g_file_get_parent(file);
		struct browser *b = parent ?
			g_hash_table_lookup(windows, parent) : NULL;
		if (b) {
			browser_select_too(b, file);
			g_object_unref(parent);
		} else {
			if (parent) {
				/* Straight there: no Home to go back to */
				b = browser_new(parent);
				browser_select_too(b, file);
				g_hash_table_insert(windows, parent, b);
			} else {
				b = browser_new(file); // the root
			}
			g_ptr_array_add(order, b);
		}
		g_object_unref(file);
	}
	for (guint i = 0; i < order->len; i++) {
		browser_present(order->pdata[i]);
	}
	g_ptr_array_unref(order);
	g_hash_table_unref(windows);
}

static void fm_call(GDBusConnection *conn, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *inv, gpointer data) {
	const char **uris;
	const char *token;
	g_variant_get(params, "(^a&s&s)", &uris, &token);
	/* The first window presented takes the token */
	c8ui_app_set_launch_token(fm_app, token);
	if (g_strcmp0(method, "ShowFolders") == 0) {
		show_folders(uris);
	} else {
		show_items(uris);
	}
	c8ui_app_set_launch_token(fm_app, NULL);
	g_free(uris);
	g_dbus_method_invocation_return_value(inv, NULL);
}

static const GDBusInterfaceVTable fm_vtable = {
	.method_call = fm_call,
};

void filemanager_init(struct c8ui_app *app) {
	fm_app = app;
	GError *error = NULL;
	GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
	if (bus == NULL) {
		g_error_free(error);
		return;
	}
	GDBusNodeInfo *info = g_dbus_node_info_new_for_xml(fm_xml, NULL);
	if (g_dbus_connection_register_object(bus, PATH, info->interfaces[0],
			&fm_vtable, NULL, NULL, &error) == 0) {
		fprintf(stderr, "c8-files: no FileManager1: %s\n", error->message);
		g_error_free(error);
	} else {
		/* Another file manager may have it: then it stays theirs */
		g_bus_own_name_on_connection(bus, NAME,
			G_BUS_NAME_OWNER_FLAGS_NONE, NULL, NULL, NULL, NULL);
	}
	g_dbus_node_info_unref(info);
	/* bus stays: the object is served on it for the app's life */
}
