/*
 * The places down the side: home and its usual folders, the Trash, what
 * was pinned (folders are GTK's bookmarks, shared with other file
 * managers; files, which those can't hold, are ours in files.ini), then
 * drives: this PC,
 * what is mounted and what could be (a USB stick plugged in, unmounted
 * partitions), from GIO's volume monitor, which covers gvfs too.
 */
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include "files.h"

struct watch {
	guint id;
	places_fn fn;
	void *data;
};

static GVolumeMonitor *monitor;
static GPtrArray *places; // struct place
static GPtrArray *watches; // struct watch
static GFileMonitor *bookmarks_monitor;
static guint next_watch = 1;

static void place_free(gpointer data) {
	struct place *p = data;
	g_free(p->name);
	g_free(p->icon);
	g_clear_object(&p->file);
	g_clear_object(&p->mount);
	g_clear_object(&p->volume);
	free(p);
}

static struct place *add(enum place_kind kind, const char *name,
		const char *icon, GFile *file) {
	struct place *p = calloc(1, sizeof(*p));
	p->kind = kind;
	p->name = g_strdup(name);
	p->icon = g_strdup(icon);
	p->file = file; // taken
	g_ptr_array_add(places, p);
	return p;
}

static void add_dir(const char *path, const char *icon) {
	if (path && g_file_test(path, G_FILE_TEST_IS_DIR)) {
		GFile *file = g_file_new_for_path(path);
		char *name = folder_title_real(file);
		add(PLACE_FOLDER, name, icon, file);
		g_free(name);
	}
}

static char *icon_name(GIcon *icon, const char *fallback) {
	char *name = NULL;
	if (icon && G_IS_THEMED_ICON(icon)) {
		const char *const *names = g_themed_icon_get_names(G_THEMED_ICON(icon));
		for (int i = 0; names[i] && name == NULL; i++) {
			if (icon_named(names[i])) {
				name = g_strdup(names[i]);
			}
		}
	}
	return name ? name : g_strdup(fallback);
}

static char *bookmarks_path(void) {
	return g_build_filename(g_get_user_config_dir(), "gtk-3.0", "bookmarks",
		NULL);
}

static char *pins_path(void) {
	return g_build_filename(g_get_user_config_dir(), "cont8nuum", "files.ini",
		NULL);
}

/* Pinned files, as URIs */
static char **pinned_files(void) {
	char *path = pins_path();
	GKeyFile *kf = g_key_file_new();
	g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL);
	char **uris = g_key_file_get_string_list(kf, "pins", "files", NULL, NULL);
	g_key_file_free(kf);
	g_free(path);
	return uris ? uris : g_new0(char *, 1);
}

static void save_pinned_files(char **uris) {
	char *path = pins_path();
	GKeyFile *kf = g_key_file_new();
	/* The view's settings are in there too */
	g_key_file_load_from_file(kf, path, G_KEY_FILE_KEEP_COMMENTS, NULL);
	g_key_file_set_string_list(kf, "pins", "files",
		(const char *const *)uris, g_strv_length(uris));
	char *dir = g_path_get_dirname(path);
	g_mkdir_with_parents(dir, 0700);
	g_free(dir);
	GError *error = NULL;
	if (!g_key_file_save_to_file(kf, path, &error)) {
		g_warning("Can't save %s: %s", path, error->message);
		g_error_free(error);
	}
	g_key_file_free(kf);
	g_free(path);
}

static void add_pinned_files(bool heading) {
	char **uris = pinned_files();
	for (char **u = uris; *u; u++) {
		GFile *file = g_file_new_for_uri(*u);
		GFileInfo *info = g_file_query_info(file,
			G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME ","
			G_FILE_ATTRIBUTE_STANDARD_ICON, G_FILE_QUERY_INFO_NONE, NULL,
			NULL);
		if (info == NULL) {
			/* Gone (or its drive is): not shown, but still pinned */
			g_object_unref(file);
			continue;
		}
		if (!heading) {
			add(PLACE_HEADING, "Pinned", NULL, NULL);
			heading = true;
		}
		char *icon = icon_name(g_file_info_get_icon(info), "text-x-generic");
		struct place *p = add(PLACE_FOLDER,
			g_file_info_get_display_name(info), icon, file);
		p->pinned = p->is_file = true;
		g_free(icon);
		g_object_unref(info);
	}
	g_strfreev(uris);
}

/* Listed already, itself (places_find also says yes for what's inside
 * one, and a folder in Home is worth pinning) */
static bool is_place(GFile *file) {
	for (guint i = 0; i < places->len; i++) {
		struct place *p = places->pdata[i];
		if (p->file && g_file_equal(p->file, file)) {
			return true;
		}
	}
	return false;
}

static void add_bookmarks(void) {
	char *path = bookmarks_path();
	char *text = NULL;
	g_file_get_contents(path, &text, NULL, NULL);
	g_free(path);
	bool heading = false;
	if (text == NULL) {
		add_pinned_files(heading);
		return;
	}
	char **lines = g_strsplit(text, "\n", -1);
	for (char **l = lines; *l; l++) {
		if (**l == '\0') {
			continue;
		}
		/* "URI name", the name optional */
		char *space = strchr(*l, ' ');
		char *uri = space ? g_strndup(*l, space - *l) : g_strdup(*l);
		GFile *file = g_file_new_for_uri(uri);
		g_free(uri);
		/* Gone, or one of the usual folders already listed; a server's
		 * can't be asked before it is connected to */
		if ((g_file_is_native(file) && !g_file_query_exists(file, NULL)) ||
				is_place(file)) {
			g_object_unref(file);
			continue;
		}
		if (!heading) {
			add(PLACE_HEADING, "Pinned", NULL, NULL);
			heading = true;
		}
		char *name = space && space[1] ? g_strdup(space + 1) :
			folder_title_real(file);
		struct place *p = add(PLACE_FOLDER, name, g_file_is_native(file) ?
			"folder" : "folder-remote", file);
		p->pinned = true;
		g_free(name);
	}
	g_strfreev(lines);
	g_free(text);
	add_pinned_files(heading);
}

/* Computers and shares around, if gvfs can look (its network backend) */
static void add_network(void) {
	const char *const *schemes =
		g_vfs_get_supported_uri_schemes(g_vfs_get_default());
	if (schemes && g_strv_contains(schemes, "network")) {
		add(PLACE_HEADING, "Network", NULL, NULL);
		add(PLACE_FOLDER, "Network", "network-workgroup",
			g_file_new_for_uri("network:///"));
	}
}

void places_add_bookmark(const char *uri) {
	char *path = bookmarks_path();
	char *text = NULL;
	g_file_get_contents(path, &text, NULL, NULL);
	/* Once is enough */
	char **lines = g_strsplit(text ? text : "", "\n", -1);
	bool there = false;
	for (char **l = lines; *l && !there; l++) {
		char *space = strchr(*l, ' ');
		there = space ? strncmp(*l, uri, space - *l) == 0 &&
			strlen(uri) == (size_t)(space - *l) : strcmp(*l, uri) == 0;
	}
	g_strfreev(lines);
	if (!there) {
		GString *s = g_string_new(text ? text : "");
		if (s->len > 0 && s->str[s->len - 1] != '\n') {
			g_string_append_c(s, '\n');
		}
		g_string_append_printf(s, "%s\n", uri);
		char *dir = g_path_get_dirname(path);
		g_mkdir_with_parents(dir, 0700);
		g_free(dir);
		GError *error = NULL;
		if (!g_file_set_contents(path, s->str, s->len, &error)) {
			g_warning("Can't save %s: %s", path, error->message);
			g_error_free(error);
		}
		g_string_free(s, TRUE);
	}
	g_free(text);
	g_free(path);
}

static void changed(void);

/* Takes uri's line out of GTK's bookmarks */
static void remove_bookmark(const char *uri) {
	char *path = bookmarks_path();
	char *text = NULL;
	if (g_file_get_contents(path, &text, NULL, NULL)) {
		GString *s = g_string_new(NULL);
		char **lines = g_strsplit(text, "\n", -1);
		size_t n = strlen(uri);
		for (char **l = lines; *l; l++) {
			bool it = strncmp(*l, uri, n) == 0 &&
				((*l)[n] == '\0' || (*l)[n] == ' ');
			if (!it && **l) {
				g_string_append_printf(s, "%s\n", *l);
			}
		}
		g_strfreev(lines);
		GError *error = NULL;
		if (!g_file_set_contents(path, s->str, s->len, &error)) {
			g_warning("Can't save %s: %s", path, error->message);
			g_error_free(error);
		}
		g_string_free(s, TRUE);
		g_free(text);
	}
	g_free(path);
}

void places_pin(GFile *file, bool dir) {
	char *uri = g_file_get_uri(file);
	if (dir) {
		places_add_bookmark(uri);
	} else {
		char **uris = pinned_files();
		if (!g_strv_contains((const char *const *)uris, uri)) {
			guint n = g_strv_length(uris);
			uris = g_renew(char *, uris, n + 2);
			uris[n] = g_strdup(uri);
			uris[n + 1] = NULL;
			save_pinned_files(uris);
		}
		g_strfreev(uris);
	}
	g_free(uri);
	changed(); // now, not when the monitor gets round to it
}

void places_unpin(GFile *file) {
	char *uri = g_file_get_uri(file);
	char **uris = pinned_files();
	GPtrArray *left = g_ptr_array_new();
	for (char **u = uris; *u; u++) {
		if (strcmp(*u, uri) != 0) {
			g_ptr_array_add(left, *u);
		}
	}
	if (left->len != g_strv_length(uris)) {
		g_ptr_array_add(left, NULL);
		save_pinned_files((char **)left->pdata);
	}
	g_ptr_array_unref(left);
	g_strfreev(uris);
	remove_bookmark(uri);
	g_free(uri);
	changed();
}

static void add_drives(void) {
	add(PLACE_HEADING, "Drives", NULL, NULL);
	add(PLACE_DRIVE, "This PC", "drive-harddisk", g_file_new_for_path("/"));

	GList *mounts = g_volume_monitor_get_mounts(monitor);
	for (GList *l = mounts; l; l = l->next) {
		GMount *m = l->data;
		if (g_mount_is_shadowed(m)) {
			continue;
		}
		GFile *root = g_mount_get_root(m);
		char *path = g_file_get_path(root);
		/* The system's own, already "This PC"; and an archive being
		 * looked into is no drive: it's found where its file is */
		bool system = (path && strcmp(path, "/") == 0) ||
			g_file_has_uri_scheme(root, "archive");
		g_free(path);
		if (system) {
			g_object_unref(root);
			continue;
		}
		char *name = g_mount_get_name(m);
		GIcon *gicon = g_mount_get_icon(m);
		char *icon = icon_name(gicon, "drive-removable-media");
		struct place *p = add(PLACE_DRIVE, name, icon, root);
		p->mount = g_object_ref(m);
		p->can_eject = g_mount_can_eject(m) || g_mount_can_unmount(m);
		g_free(icon);
		g_clear_object(&gicon);
		g_free(name);
	}
	g_list_free_full(mounts, g_object_unref);

	/* Partitions and media that could be mounted: opening one does it */
	GList *volumes = g_volume_monitor_get_volumes(monitor);
	for (GList *l = volumes; l; l = l->next) {
		GVolume *v = l->data;
		GMount *m = g_volume_get_mount(v);
		if (m) {
			g_object_unref(m);
			continue;
		}
		if (!g_volume_can_mount(v)) {
			continue;
		}
		char *name = g_volume_get_name(v);
		GIcon *gicon = g_volume_get_icon(v);
		char *icon = icon_name(gicon, "drive-harddisk");
		struct place *p = add(PLACE_DRIVE, name, icon, NULL);
		p->volume = g_object_ref(v);
		p->can_eject = g_volume_can_eject(v);
		g_free(icon);
		g_clear_object(&gicon);
		g_free(name);
	}
	g_list_free_full(volumes, g_object_unref);
}

static void build(void) {
	if (places) {
		g_ptr_array_unref(places);
	}
	places = g_ptr_array_new_with_free_func(place_free);
	add_dir(g_get_home_dir(), "user-home");
	add_dir(g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP), "user-desktop");
	add_dir(g_get_user_special_dir(G_USER_DIRECTORY_DOCUMENTS),
		"folder-documents");
	add_dir(g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD),
		"folder-download");
	add_dir(g_get_user_special_dir(G_USER_DIRECTORY_MUSIC), "folder-music");
	add_dir(g_get_user_special_dir(G_USER_DIRECTORY_PICTURES),
		"folder-pictures");
	add_dir(g_get_user_special_dir(G_USER_DIRECTORY_VIDEOS), "folder-videos");
	add(PLACE_FOLDER, "Trash", "user-trash", g_file_new_for_uri("trash:///"));
	add_bookmarks();
	add_drives();
	add_network();
}

static void changed(void) {
	build();
	for (guint i = 0; i < watches->len; i++) {
		struct watch *w = watches->pdata[i];
		w->fn(w->data);
	}
}

static void volumes_changed(GVolumeMonitor *m, gpointer object,
		gpointer data) {
	changed();
}

static void bookmarks_changed(GFileMonitor *m, GFile *file, GFile *other,
		GFileMonitorEvent event, gpointer data) {
	if (event == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT ||
			event == G_FILE_MONITOR_EVENT_DELETED ||
			event == G_FILE_MONITOR_EVENT_CREATED) {
		changed();
	}
}

void places_init(void) {
	if (monitor) {
		return;
	}
	watches = g_ptr_array_new_with_free_func(free);
	monitor = g_volume_monitor_get();
	const char *signals[] = {
		"mount-added", "mount-removed", "mount-changed",
		"volume-added", "volume-removed", "volume-changed",
	};
	for (size_t i = 0; i < G_N_ELEMENTS(signals); i++) {
		g_signal_connect(monitor, signals[i], G_CALLBACK(volumes_changed),
			NULL);
	}
	char *path = bookmarks_path();
	GFile *file = g_file_new_for_path(path);
	bookmarks_monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL,
		NULL);
	if (bookmarks_monitor) {
		g_signal_connect(bookmarks_monitor, "changed",
			G_CALLBACK(bookmarks_changed), NULL);
	}
	g_object_unref(file);
	g_free(path);
	build();
}

GPtrArray *places_get(void) {
	return places;
}

guint places_watch(places_fn fn, void *data) {
	struct watch *w = calloc(1, sizeof(*w));
	w->id = next_watch++;
	w->fn = fn;
	w->data = data;
	g_ptr_array_add(watches, w);
	return w->id;
}

void places_unwatch(guint id) {
	for (guint i = 0; i < watches->len; i++) {
		struct watch *w = watches->pdata[i];
		if (w->id == id) {
			g_ptr_array_remove_index(watches, i);
			return;
		}
	}
}

int places_find(GFile *dir) {
	if (places == NULL) {
		return -1;
	}
	int best = -1;
	int best_depth = -1;
	for (guint i = 0; i < places->len; i++) {
		struct place *p = places->pdata[i];
		if (p->file == NULL || p->is_file) {
			continue;
		}
		if (!g_file_equal(p->file, dir) && !g_file_has_prefix(dir, p->file)) {
			continue;
		}
		/* The deepest: Pictures over Home for a folder in Pictures */
		char *uri = g_file_get_uri(p->file);
		int depth = strlen(uri);
		g_free(uri);
		if (depth > best_depth) {
			best = i;
			best_depth = depth;
		}
	}
	return best;
}
