/*
 * The user's files by name, for search: recently used files
 * (recently-used.xbel) and the whole home folder, plus any XDG folder
 * (Documents, Pictures, ...) kept outside it. Names only, no contents and
 * no indexer daemon: it is built on a worker thread shortly after startup
 * and again when search opens, if it is more than a minute old. Hidden
 * folders are left out; the walk goes breadth first, so if there are more
 * than FILES_MAX it is the deepest that are missed.
 */
#define _GNU_SOURCE
#include <dirent.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <gio/gio.h>
#include "shell.h"

#define FILES_MAX 100000
#define WALK_DEPTH 12
#define STALE_US (60 * G_USEC_PER_SEC)
#define FIRST_BUILD_MS 5000

/* The index is two blocks, not an allocation or three per file: with a
 * hundred thousand files that was 18 MB of the shell, now about 5. Every
 * folder's path is in the text once; an entry says which folder and where
 * its name is, the name followed by its casefolded form when that's
 * another string. Paths are put together for the few that are shown. */
#define HAS_KEY 1
#define IS_DIR 2

struct file_entry {
	uint32_t dir, name; // in the text: the folder's path, the name
	uint32_t used; // last used, in seconds, 0 for never
	uint8_t name_len, depth; // depth: folders below home
	uint8_t flags;
};

struct index {
	struct file_entry *entries;
	guint count;
	char *text;
};

struct build {
	char **roots; // home first
	GArray *entries;
	GByteArray *text;
	GHashTable *seen; // the recent files' paths, not to list them twice
	GString *path; // of the file in hand
	struct index *done;
};

static struct {
	struct index *index;
	GPtrArray *hit_paths; // the last search's
	int64_t built_at;
	bool building;
	void (*changed)(void);
	guint first;
} fl;

static void index_free(struct index *ix) {
	if (ix) {
		g_free(ix->entries);
		g_free(ix->text);
		g_free(ix);
	}
}

static uint32_t add_text(struct build *b, const char *s) {
	uint32_t at = b->text->len;
	g_byte_array_append(b->text, (const guint8 *)s, strlen(s) + 1);
	return at;
}

static int depth_of(const char *dir) {
	const char *home = g_get_home_dir();
	size_t hlen = strlen(home);
	const char *p = strncmp(dir, home, hlen) == 0 ? dir + hlen : dir;
	int depth = 1; // the file's own slash
	for (; *p; p++) {
		depth += *p == '/';
	}
	return depth > 255 ? 255 : depth;
}

/* A file called name in the folder whose path is at dir in the text */
static void add(struct build *b, uint32_t dir, int depth, const char *name,
		bool is_dir, int64_t used) {
	size_t len = strlen(name);
	if (b->entries->len >= FILES_MAX || len == 0 || len > 255) {
		return;
	}
	struct file_entry e = {
		.dir = dir, .name = add_text(b, name), .name_len = (uint8_t)len,
		.used = used > 0 ? (uint32_t)MIN(used, (int64_t)UINT32_MAX) : 0,
		.depth = (uint8_t)depth, .flags = is_dir ? IS_DIR : 0,
	};
	/* Plain lower case folds to itself, which is most names */
	bool plain = true;
	for (const char *p = name; *p && plain; p++) {
		plain = (unsigned char)*p < 0x80 && !g_ascii_isupper(*p);
	}
	if (!plain) {
		char *key = g_utf8_casefold(name, -1);
		if (strcmp(key, name) != 0) {
			add_text(b, key);
			e.flags |= HAS_KEY;
		}
		g_free(key);
	}
	g_array_append_val(b->entries, e);
}

/* Folders nobody looks for files in, which can hold thousands: build
 * output, packages, and the Windows inside Wine prefixes */
static bool skip_dir(const char *name) {
	static const char *const names[] = {
		"node_modules", "__pycache__", "target", "venv", "site-packages",
		"drive_c",
	};
	for (size_t i = 0; i < G_N_ELEMENTS(names); i++) {
		if (strcmp(name, names[i]) == 0) {
			return true;
		}
	}
	return false;
}

struct pending {
	uint32_t dir; // its path, in the text
	int depth; // how far down the walk is
};

/* Symlinks are listed but not followed, so a loop can't trap the walk */
static void walk(struct build *b, const char *root) {
	GQueue queue = G_QUEUE_INIT;
	struct pending *first = g_new(struct pending, 1);
	*first = (struct pending){ add_text(b, root), 0 };
	g_queue_push_tail(&queue, first);
	struct pending *p;
	while ((p = g_queue_pop_head(&queue)) != NULL) {
		/* A copy: the text moves as it grows */
		g_string_assign(b->path, (const char *)b->text->data + p->dir);
		gsize dir_len = b->path->len;
		int depth = depth_of(b->path->str);
		DIR *d = b->entries->len < FILES_MAX ? opendir(b->path->str) : NULL;
		struct dirent *ent;
		while (d && (ent = readdir(d)) != NULL &&
				b->entries->len < FILES_MAX) {
			if (ent->d_name[0] == '.') {
				continue;
			}
			g_string_truncate(b->path, dir_len);
			if (dir_len == 0 || b->path->str[dir_len - 1] != '/') {
				g_string_append_c(b->path, '/');
			}
			g_string_append(b->path, ent->d_name);
			bool is_dir = ent->d_type == DT_DIR;
			if (ent->d_type == DT_UNKNOWN) {
				struct stat st;
				is_dir = lstat(b->path->str, &st) == 0 && S_ISDIR(st.st_mode);
			}
			if (!g_hash_table_contains(b->seen, b->path->str)) {
				add(b, p->dir, depth, ent->d_name, is_dir, 0);
			}
			if (is_dir && p->depth < WALK_DEPTH && !skip_dir(ent->d_name)) {
				struct pending *next = g_new(struct pending, 1);
				*next = (struct pending){ add_text(b, b->path->str),
					p->depth + 1 };
				g_queue_push_tail(&queue, next);
			}
		}
		if (d) {
			closedir(d);
		}
		g_free(p);
	}
}

static void add_recent(struct build *b) {
	char *path = g_build_filename(g_get_user_data_dir(),
		"recently-used.xbel", NULL);
	GBookmarkFile *bf = g_bookmark_file_new();
	if (g_bookmark_file_load_from_file(bf, path, NULL)) {
		gsize n = 0;
		char **uris = g_bookmark_file_get_uris(bf, &n);
		for (gsize i = 0; i < n; i++) {
			char *file = g_filename_from_uri(uris[i], NULL, NULL);
			struct stat st;
			if (file && stat(file, &st) == 0) {
				GDateTime *when = g_bookmark_file_get_visited_date_time(bf,
					uris[i], NULL);
				if (when == NULL) {
					when = g_bookmark_file_get_modified_date_time(bf,
						uris[i], NULL);
				}
				char *dir = g_path_get_dirname(file);
				char *name = g_path_get_basename(file);
				if (!g_hash_table_contains(b->seen, file)) {
					add(b, add_text(b, dir), depth_of(dir), name,
						S_ISDIR(st.st_mode),
						when ? g_date_time_to_unix(when) : 1);
					g_hash_table_add(b->seen, g_strdup(file));
				}
				g_free(dir);
				g_free(name);
			}
			g_free(file);
		}
		g_strfreev(uris);
	}
	g_bookmark_file_free(bf);
	g_free(path);
}

static void build_thread(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	struct build *b = data;
	add_recent(b);
	for (char **root = b->roots; *root; root++) {
		walk(b, *root);
	}
	/* At their size: the arrays grew by doubling */
	struct index *ix = g_new0(struct index, 1);
	ix->count = b->entries->len;
	ix->entries = g_memdup2(b->entries->data,
		(gsize)ix->count * sizeof(struct file_entry));
	ix->text = g_memdup2(b->text->data, b->text->len);
	b->done = ix;
	g_array_set_size(b->entries, 0);
	g_byte_array_set_size(b->text, 0);
	g_task_return_boolean(task, TRUE);
}

static void build_free(gpointer data) {
	struct build *b = data;
	g_strfreev(b->roots);
	g_array_unref(b->entries);
	g_byte_array_unref(b->text);
	g_hash_table_destroy(b->seen);
	g_string_free(b->path, TRUE);
	index_free(b->done);
	g_free(b);
}

static void build_done(GObject *source, GAsyncResult *res, gpointer data) {
	struct build *b = g_task_get_task_data(G_TASK(res));
	fl.building = false;
	fl.built_at = g_get_monotonic_time();
	index_free(fl.index);
	fl.index = b->done;
	b->done = NULL;
	g_clear_pointer(&fl.hit_paths, g_ptr_array_unref);
	if (fl.changed) {
		fl.changed();
	}
}

static void build(void) {
	if (fl.building) {
		return;
	}
	fl.building = true;
	struct build *b = g_new0(struct build, 1);
	/* g_get_user_special_dir isn't for threads: asked here */
	static const GUserDirectory dirs[] = {
		G_USER_DIRECTORY_DESKTOP, G_USER_DIRECTORY_DOCUMENTS,
		G_USER_DIRECTORY_DOWNLOAD, G_USER_DIRECTORY_MUSIC,
		G_USER_DIRECTORY_PICTURES, G_USER_DIRECTORY_VIDEOS,
	};
	const char *home = g_get_home_dir();
	size_t hlen = strlen(home);
	GPtrArray *roots = g_ptr_array_new();
	g_ptr_array_add(roots, g_strdup(home));
	for (size_t i = 0; i < G_N_ELEMENTS(dirs); i++) {
		/* Only those outside home: the rest are walked with it */
		const char *dir = g_get_user_special_dir(dirs[i]);
		if (dir && !(strncmp(dir, home, hlen) == 0 &&
				(dir[hlen] == '/' || dir[hlen] == '\0'))) {
			g_ptr_array_add(roots, g_strdup(dir));
		}
	}
	g_ptr_array_add(roots, NULL);
	b->roots = (char **)g_ptr_array_free(roots, FALSE);
	b->entries = g_array_new(FALSE, FALSE, sizeof(struct file_entry));
	b->text = g_byte_array_new();
	b->seen = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
	b->path = g_string_new(NULL);
	GTask *task = g_task_new(NULL, NULL, build_done, NULL);
	g_task_set_task_data(task, b, build_free);
	g_task_run_in_thread(task, build_thread);
	g_object_unref(task);
}

static gboolean first_build(gpointer data) {
	fl.first = 0;
	build();
	return G_SOURCE_REMOVE;
}

void files_init(void (*changed)(void)) {
	fl.changed = changed;
	fl.first = g_timeout_add(FIRST_BUILD_MS, first_build, NULL);
}

void files_refresh(void) {
	if (fl.index == NULL ||
			g_get_monotonic_time() - fl.built_at > STALE_US) {
		build();
	}
}

/* Better matches first; among equals, the most recently used, then the
 * least buried, then the shortest name */
static bool better(int score, const struct file_entry *e,
		const struct file_hit *than) {
	if (score != than->score) {
		return score > than->score;
	}
	if ((int64_t)e->used != than->used) {
		return (int64_t)e->used > than->used;
	}
	if (e->depth != than->depth) {
		return e->depth < than->depth;
	}
	return e->name_len < strlen(than->name);
}

int files_search(const char *query, struct file_hit *out, int max) {
	int n = 0;
	struct index *ix = fl.index;
	g_clear_pointer(&fl.hit_paths, g_ptr_array_unref);
	for (guint i = 0; ix && i < ix->count; i++) {
		const struct file_entry *e = &ix->entries[i];
		const char *name = ix->text + e->name;
		const char *key = e->flags & HAS_KEY ? name + e->name_len + 1 : name;
		int score = search_fuzzy(key, name, query);
		if (score == 0 || (n == max && !better(score, e, &out[n - 1]))) {
			continue;
		}
		/* Insertion into the sorted few */
		int at = n < max ? n++ : max - 1;
		while (at > 0 && better(score, e, &out[at - 1])) {
			out[at] = out[at - 1];
			at--;
		}
		out[at] = (struct file_hit){
			.folder = ix->text + e->dir, .name = name,
			.dir = e->flags & IS_DIR, .depth = e->depth, .used = e->used,
			.score = score,
		};
	}
	/* Their paths, ours until the next search */
	fl.hit_paths = g_ptr_array_new_with_free_func(g_free);
	for (int i = 0; i < n; i++) {
		char *path = g_build_filename(out[i].folder, out[i].name, NULL);
		g_ptr_array_add(fl.hit_paths, path);
		out[i].path = path;
	}
	return n;
}
