/*
 * c8-files: one copy runs (c8ui_app_main). Launched with folders it
 * opens a window on each, with files a window on their folder with them
 * selected, with nothing a window on Home. --portal is how D-Bus starts
 * it for a file picker or a FileManager1 call: no window then, only
 * what the call asks for.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <c8ui/c8ui-charms.h>
#include "files.h"

#define RESULTS 30

static struct {
	struct c8ui_app *app;
	struct c8ui_charms *charms;
	bool portal_start; // started for the portal: no window at first
} g;

struct c8ui_app *files_app(void) {
	return g.app;
}

/* Search: the folder in front, by name */

static void search(struct c8ui_search *s, const char *query, void *data) {
	struct browser *b = browser_last();
	if (b == NULL || query[0] == '\0') {
		if (b) {
			browser_search(b, NULL);
		}
		return;
	}
	browser_search(b, query);
	/* The shell's pane lists them too, to pick one there */
	GFile *dir = browser_folder(b);
	GFileEnumerator *en = g_file_enumerate_children(dir,
		G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME ","
		G_FILE_ATTRIBUTE_STANDARD_NAME "," G_FILE_ATTRIBUTE_STANDARD_ICON ","
		G_FILE_ATTRIBUTE_STANDARD_IS_HIDDEN, G_FILE_QUERY_INFO_NONE, NULL,
		NULL);
	char *folded = g_utf8_casefold(query, -1);
	char *where = folder_title(dir);
	GFileInfo *info;
	int n = 0;
	while (en && n < RESULTS &&
			(info = g_file_enumerator_next_file(en, NULL, NULL))) {
		const char *name = g_file_info_get_display_name(info);
		char *f = g_utf8_casefold(name, -1);
		if (!g_file_info_get_is_hidden(info) && strstr(f, folded)) {
			GFile *child = g_file_enumerator_get_child(en, info);
			char *uri = g_file_get_uri(child);
			GIcon *icon = g_file_info_get_icon(info);
			const char *icon_name = icon && G_IS_THEMED_ICON(icon) ?
				g_themed_icon_get_names(G_THEMED_ICON(icon))[0] : NULL;
			c8ui_search_add(s, uri, name, where, icon_name);
			g_free(uri);
			g_object_unref(child);
			n++;
		}
		g_free(f);
		g_object_unref(info);
	}
	g_free(where);
	g_free(folded);
	g_clear_object(&en);
}

static void search_open(const char *id, const char *query, void *data) {
	struct browser *b = browser_last();
	if (b == NULL) {
		return;
	}
	GFile *file = g_file_new_for_uri(id);
	browser_search(b, NULL);
	browser_reveal(b, file);
	g_object_unref(file);
}

static void search_submit(const char *query, void *data) {
	struct browser *b = browser_last();
	if (b) {
		browser_search(b, query);
	}
}

/* Settings: how folders are shown, everywhere */

static const char *const sort_names[] = {
	[SORT_NAME] = "Name",
	[SORT_MODIFIED] = "Date modified",
	[SORT_TYPE] = "Type",
	[SORT_SIZE] = "Size",
};

static void option_changed(struct c8ui_setting *s, void *data) {
	const char *id = c8ui_setting_id(s);
	if (strcmp(id, "view") == 0) {
		prefs.details = c8ui_setting_get_int(s) == 1;
	} else if (strcmp(id, "sort") == 0) {
		int i = c8ui_setting_get_int(s);
		if (i >= 0 && i < (int)G_N_ELEMENTS(sort_names)) {
			prefs.sort = i;
		}
	} else if (strcmp(id, "descending") == 0) {
		prefs.descending = c8ui_setting_get_bool(s);
	} else if (strcmp(id, "hidden") == 0) {
		prefs.show_hidden = c8ui_setting_get_bool(s);
	} else if (strcmp(id, "thumbnails") == 0) {
		prefs.thumbnails = c8ui_setting_get_bool(s);
	}
	prefs_changed();
}

static void options_page(struct c8ui_settings_page *page, void *data) {
	static const char *const views[] = { "Tiles", "Details" };
	c8ui_page_buttons(page, "view", "Show items as", views, 2,
		prefs.details ? 1 : 0, option_changed, NULL);
	c8ui_page_choice(page, "sort", "Sort by", sort_names,
		G_N_ELEMENTS(sort_names), prefs.sort, option_changed, NULL);
	struct c8ui_setting *s = c8ui_page_toggle(page, "descending",
		"Reverse order", prefs.descending, option_changed, NULL);
	c8ui_setting_set_description(s, "Z to A, newest, or biggest first. "
		"Folders still come first.");
	s = c8ui_page_toggle(page, "hidden", "Show hidden items",
		prefs.show_hidden, option_changed, NULL);
	c8ui_setting_set_description(s, "Files and folders whose names start "
		"with a dot. Ctrl+H shows or hides them too.");
	s = c8ui_page_toggle(page, "thumbnails", "Show thumbnails",
		prefs.thumbnails, option_changed, NULL);
	c8ui_setting_set_description(s, "Pictures, videos and documents show "
		"what's in them instead of an icon.");
}

static void prefs_shown(void) {
	if (g.charms) {
		c8ui_charms_changed(g.charms, "options");
	}
}

/* The app */

static void startup(struct c8ui_app *app, void *data) {
	g.app = app;
	prefs_load();
	places_init();
	portal_init(app);
	filemanager_init(app);
	c8ui_app_on_clipboard(app, browsers_clipboard_changed, NULL);
	g.charms = c8ui_charms_new(app);
	if (g.charms) {
		c8ui_charms_on_search(g.charms, search, search_open, search_submit,
			NULL);
		c8ui_charms_add_page(g.charms, "options", "Options", options_page,
			NULL);
		prefs_watch(prefs_shown);
	}
}

static void open(struct c8ui_app *app, char **uris, void *data) {
	if (g.portal_start) {
		g.portal_start = false;
		if (uris[0] == NULL) {
			/* Only the picker is wanted: its call comes once we have
			 * the portal's name */
			portal_expect();
			return;
		}
	}
	if (uris[0] == NULL) {
		browser_present(browser_new(NULL));
		return;
	}
	for (int i = 0; uris[i]; i++) {
		GFile *file = g_file_new_for_uri(uris[i]);
		GFileType type = g_file_query_file_type(file, G_FILE_QUERY_INFO_NONE,
			NULL);
		struct browser *b;
		char *mime = NULL;
		if (type == G_FILE_TYPE_REGULAR) {
			GFileInfo *info = g_file_query_info(file,
				G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
				G_FILE_QUERY_INFO_NONE, NULL, NULL);
			if (info) {
				mime = g_strdup(g_file_info_get_content_type(info));
				g_object_unref(info);
			}
		}
		if (type == G_FILE_TYPE_DIRECTORY || type == G_FILE_TYPE_MOUNTABLE ||
				type == G_FILE_TYPE_UNKNOWN) {
			b = browser_new(file);
		} else if (arc_can_browse(mime)) {
			/* An archive opened from elsewhere (we're its default
			 * app) opens like a folder, as Enter on it does */
			GFile *root = arc_root(file);
			b = browser_new(root);
			g_object_unref(root);
		} else {
			b = browser_new(NULL);
			browser_reveal(b, file);
		}
		browser_present(b);
		g_free(mime);
		g_object_unref(file);
	}
}

static void shutdown(struct c8ui_app *app, void *data) {
	c8ui_charms_destroy(g.charms);
}

int main(int argc, char **argv) {
	/* Ours, before c8ui sees the rest as files */
	int n = 1;
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "--portal") == 0) {
			g.portal_start = true;
		} else {
			argv[n++] = argv[i];
		}
	}
	argv[n] = NULL;
	static const struct c8ui_app_info info = {
		.id = APP_ID,
		.startup = startup,
		.open = open,
		.shutdown = shutdown,
	};
	return c8ui_app_main(&info, n, argv);
}
