/*
 * What is in a folder: its pictures (by the types glycin can decode) and
 * its folders, hidden ones left out, read on a thread and sorted the way
 * Files sorts (folders first, names with numbers in order).
 */
#include <stdio.h>
#include <string.h>
#include <glycin.h>
#include <c8ui/c8ui-files.h>
#include "photos.h"

struct ph_entry *ph_entry_ref(struct ph_entry *e) {
	e->refs++;
	return e;
}

void ph_entry_unref(struct ph_entry *e) {
	if (e == NULL || --e->refs > 0) {
		return;
	}
	if (e->thumb_load) {
		c8ui_thumbnail_cancel(e->thumb_load);
	}
	if (e->thumb) {
		cairo_surface_destroy(e->thumb);
	}
	g_free(e->uri);
	g_free(e->name);
	g_free(e->mime);
	g_free(e->collate);
	g_free(e);
}

static GHashTable *mimes; // the types glycin decodes

static bool ph_is_picture(const char *mime) {
	if (mime == NULL) {
		return false;
	}
	if (mimes == NULL) {
		mimes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
		char **list = gly_loader_get_mime_types();
		for (int i = 0; list && list[i]; i++) {
			g_hash_table_add(mimes, g_strdup(list[i]));
		}
		g_strfreev(list);
	}
	return g_hash_table_contains(mimes, mime);
}

#define ATTRS G_FILE_ATTRIBUTE_TIME_MODIFIED "," \
	G_FILE_ATTRIBUTE_STANDARD_NAME "," \
	G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," \
	G_FILE_ATTRIBUTE_STANDARD_TYPE "," \
	G_FILE_ATTRIBUTE_STANDARD_IS_HIDDEN "," \
	G_FILE_ATTRIBUTE_STANDARD_IS_BACKUP "," \
	G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE "," \
	G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE "," \
	G_FILE_ATTRIBUTE_STANDARD_SIZE

/* Folded first: without a locale's collation capitals sorted before
 * every small letter */
static char *collate_key(const char *name) {
	char *folded = g_utf8_casefold(name, -1);
	char *key = g_utf8_collate_key_for_filename(folded, -1);
	g_free(folded);
	return key;
}

static struct ph_entry *entry_from_info(GFile *file, GFileInfo *info) {
	struct ph_entry *e = g_new0(struct ph_entry, 1);
	e->refs = 1;
	e->uri = g_file_get_uri(file);
	const char *name = g_file_info_get_display_name(info);
	e->name = g_strdup(name ? name : g_file_info_get_name(info));
	e->collate = collate_key(e->name);
	e->folder = g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY;
	if (!e->folder) {
		const char *type = g_file_info_get_content_type(info);
		if (type == NULL) {
			type = g_file_info_get_attribute_string(info,
				G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE);
		}
		e->mime = type ? g_content_type_get_mime_type(type) : NULL;
	}
	e->size = g_file_info_get_size(info);
	e->taken = g_file_info_get_attribute_uint64(info,
		G_FILE_ATTRIBUTE_TIME_MODIFIED);
	return e;
}

struct ph_entry *ph_entry_for(const char *uri) {
	GFile *file = g_file_new_for_uri(uri);
	GFileInfo *info = g_file_query_info(file, ATTRS, G_FILE_QUERY_INFO_NONE,
		NULL, NULL);
	struct ph_entry *e;
	if (info) {
		e = entry_from_info(file, info);
		g_object_unref(info);
	} else {
		e = g_new0(struct ph_entry, 1);
		e->refs = 1;
		e->uri = g_strdup(uri);
		char *base = g_file_get_basename(file);
		e->name = g_filename_display_name(base ? base : uri);
		e->collate = collate_key(e->name);
		g_free(base);
	}
	g_object_unref(file);
	return e;
}

static int compare(gconstpointer a, gconstpointer b) {
	const struct ph_entry *x = *(struct ph_entry **)a;
	const struct ph_entry *y = *(struct ph_entry **)b;
	if (x->folder != y->folder) {
		return x->folder ? -1 : 1;
	}
	int r = strcmp(x->collate, y->collate);
	return r ? r : strcmp(x->name, y->name);
}

struct listing {
	char *uri;
	bool folders;
	ph_list_fn done;
	void *data;
	GPtrArray *entries;
	char *error;
};

static void listing_free(gpointer p) {
	struct listing *l = p;
	if (l->entries) {
		g_ptr_array_unref(l->entries);
	}
	g_free(l->uri);
	g_free(l->error);
	g_free(l);
}

static void read_folder(GTask *task, gpointer src, gpointer data,
		GCancellable *cancel) {
	struct listing *l = data;
	ph_is_picture(NULL); // the table, before the main loop may ask too
	GFile *dir = g_file_new_for_uri(l->uri);
	GError *err = NULL;
	GFileEnumerator *en = g_file_enumerate_children(dir, ATTRS,
		G_FILE_QUERY_INFO_NONE, cancel, &err);
	if (en == NULL) {
		l->error = g_strdup(err->message);
		g_error_free(err);
		g_object_unref(dir);
		g_task_return_boolean(task, TRUE);
		return;
	}
	l->entries = g_ptr_array_new_with_free_func(
		(GDestroyNotify)ph_entry_unref);
	GFileInfo *info;
	GFile *child;
	while (g_file_enumerator_iterate(en, &info, &child, cancel, NULL) &&
			info) {
		if (g_file_info_get_is_hidden(info) ||
				g_file_info_get_is_backup(info)) {
			continue;
		}
		struct ph_entry *e = entry_from_info(child, info);
		if (e->folder ? l->folders : ph_is_picture(e->mime)) {
			g_ptr_array_add(l->entries, e);
		} else {
			ph_entry_unref(e);
		}
	}
	g_ptr_array_sort(l->entries, compare);
	g_object_unref(en);
	g_object_unref(dir);
	g_task_return_boolean(task, TRUE);
}

static void listed(GObject *src, GAsyncResult *res, gpointer data) {
	GTask *task = G_TASK(res);
	struct listing *l = g_task_get_task_data(task);
	GCancellable *cancel = g_task_get_cancellable(task);
	if (cancel && g_cancellable_is_cancelled(cancel)) {
		return;
	}
	l->done(l->entries, l->error, l->data);
}

void ph_list_folder(const char *uri, bool folders, GCancellable *cancel,
		ph_list_fn done, void *data) {
	struct listing *l = g_new0(struct listing, 1);
	l->uri = g_strdup(uri);
	l->folders = folders;
	l->done = done;
	l->data = data;
	GTask *task = g_task_new(NULL, cancel, listed, NULL);
	g_task_set_task_data(task, l, listing_free);
	g_task_run_in_thread(task, read_folder);
	g_object_unref(task);
}

GPtrArray *ph_pictures_of(GPtrArray *entries) {
	GPtrArray *out = g_ptr_array_new_with_free_func(
		(GDestroyNotify)ph_entry_unref);
	for (guint i = 0; entries && i < entries->len; i++) {
		struct ph_entry *e = entries->pdata[i];
		if (!e->folder) {
			g_ptr_array_add(out, ph_entry_ref(e));
		}
	}
	return out;
}

char *ph_parent_uri(const char *uri) {
	GFile *file = g_file_new_for_uri(uri);
	GFile *parent = g_file_get_parent(file);
	char *out = parent ? g_file_get_uri(parent) : NULL;
	if (parent) {
		g_object_unref(parent);
	}
	g_object_unref(file);
	return out;
}

char *ph_pictures_uri(void) {
	const char *dir = g_get_user_special_dir(G_USER_DIRECTORY_PICTURES);
	if (dir == NULL || !g_file_test(dir, G_FILE_TEST_IS_DIR)) {
		dir = g_get_home_dir();
	}
	return g_filename_to_uri(dir, NULL, NULL);
}

/* By date: every picture under a folder, as Windows 8.1's collection.
 * Reading a date out of each file is slow (gexiv2 opens it), so the
 * dates are kept in the cache by path and modification time. */

#define DATES_DEPTH 8
#define DATES_MOST 50000

static char *dates_cache_path(void) {
	return g_build_filename(g_get_user_cache_dir(), "cont8nuum",
		"photos-dates.ini", NULL);
}

static void walk(GFile *dir, int depth, struct listing *l, int *seen,
		GCancellable *cancel) {
	GFileEnumerator *en = g_file_enumerate_children(dir, ATTRS,
		G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, cancel, NULL);
	if (en == NULL) {
		return;
	}
	GFileInfo *info;
	GFile *child;
	while (*seen < DATES_MOST &&
			g_file_enumerator_iterate(en, &info, &child, cancel, NULL) &&
			info) {
		(*seen)++;
		if (g_file_info_get_is_hidden(info) ||
				g_file_info_get_is_backup(info)) {
			continue;
		}
		if (g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY) {
			if (depth < DATES_DEPTH) {
				walk(child, depth + 1, l, seen, cancel);
			}
			continue;
		}
		struct ph_entry *e = entry_from_info(child, info);
		if (ph_is_picture(e->mime)) {
			g_ptr_array_add(l->entries, e);
		} else {
			ph_entry_unref(e);
		}
	}
	g_object_unref(en);
}

static int newest_first(gconstpointer a, gconstpointer b) {
	const struct ph_entry *x = *(struct ph_entry **)a;
	const struct ph_entry *y = *(struct ph_entry **)b;
	if (x->taken != y->taken) {
		return x->taken > y->taken ? -1 : 1;
	}
	return strcmp(x->collate, y->collate);
}

static void read_dates(GTask *task, gpointer src, gpointer data,
		GCancellable *cancel) {
	struct listing *l = data;
	ph_is_picture(NULL);
	l->entries = g_ptr_array_new_with_free_func(
		(GDestroyNotify)ph_entry_unref);
	GFile *dir = g_file_new_for_uri(l->uri);
	int seen = 0;
	walk(dir, 0, l, &seen, cancel);
	g_object_unref(dir);

	/* "taken modified" by path; what isn't kept is read and kept */
	char *cache = dates_cache_path();
	GKeyFile *old = g_key_file_new();
	g_key_file_load_from_file(old, cache, G_KEY_FILE_NONE, NULL);
	GKeyFile *kept = g_key_file_new();
	bool changed = false;
	for (guint i = 0; i < l->entries->len &&
			!g_cancellable_is_cancelled(cancel); i++) {
		struct ph_entry *e = l->entries->pdata[i];
		char *path = g_filename_from_uri(e->uri, NULL, NULL);
		if (path == NULL) {
			continue;
		}
		gint64 modified = e->taken, taken = 0, m = -1;
		char *was = g_key_file_get_string(old, "dates", path, NULL);
		if (was == NULL || sscanf(was, "%" G_GINT64_FORMAT " %"
				G_GINT64_FORMAT, &taken, &m) != 2 || m != modified) {
			taken = ph_taken(path);
			changed = true;
		}
		g_free(was);
		char value[48];
		snprintf(value, sizeof(value), "%" G_GINT64_FORMAT " %"
			G_GINT64_FORMAT, taken, modified);
		g_key_file_set_string(kept, "dates", path, value);
		if (taken > 0) {
			e->taken = taken;
		}
		g_free(path);
	}
	/* Written when something was read, or pictures went (only those
	 * found are kept) */
	gsize had = 0;
	g_strfreev(g_key_file_get_keys(old, "dates", &had, NULL));
	if (!g_cancellable_is_cancelled(cancel) &&
			(changed || had != l->entries->len)) {
		char *dirname = g_path_get_dirname(cache);
		g_mkdir_with_parents(dirname, 0700);
		g_free(dirname);
		g_key_file_save_to_file(kept, cache, NULL);
	}
	g_key_file_free(old);
	g_key_file_free(kept);
	g_free(cache);
	g_ptr_array_sort(l->entries, newest_first);
	g_task_return_boolean(task, TRUE);
}

void ph_list_dates(const char *uri, GCancellable *cancel, ph_list_fn done,
		void *data) {
	struct listing *l = g_new0(struct listing, 1);
	l->uri = g_strdup(uri);
	l->done = done;
	l->data = data;
	GTask *task = g_task_new(NULL, cancel, listed, NULL);
	g_task_set_task_data(task, l, listing_free);
	g_task_run_in_thread(task, read_dates);
	g_object_unref(task);
}
