/*
 * Properties: what a file is, in a flyout over it. Folders (and several
 * items) are counted on a worker thread; their size fills in when done.
 */
#include <string.h>
#include "files.h"
#include "stealth.h"

struct props {
	struct c8ui_widget *flyout;
	struct c8ui_widget *size, *contains; // filled in by the count
	GCancellable *cancel;
	bool closed, counting;
};

struct count {
	GList *files; // GFile
	guint64 bytes;
	guint files_n, dirs_n;
};

static void count_free(gpointer data) {
	struct count *c = data;
	g_list_free_full(c->files, g_object_unref);
	g_free(c);
}

/* What is in dir, down to the bottom; links are counted, not followed */
static void walk(GFile *dir, struct count *c, GCancellable *cancel) {
	GFileEnumerator *en = g_file_enumerate_children(dir,
		G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE ","
		G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
		cancel, NULL);
	GFileInfo *info;
	while (en && (info = g_file_enumerator_next_file(en, cancel, NULL))) {
		if (g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY) {
			c->dirs_n++;
			GFile *child = g_file_enumerator_get_child(en, info);
			walk(child, c, cancel);
			g_object_unref(child);
		} else {
			c->files_n++;
			c->bytes += g_file_info_get_size(info);
		}
		g_object_unref(info);
	}
	g_clear_object(&en);
}

static void count_thread(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	struct count *c = data;
	/* Of one folder, what's in it; of several items, them too */
	bool several = c->files && c->files->next;
	for (GList *l = c->files; l; l = l->next) {
		GFileInfo *info = g_file_query_info(l->data,
			G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE,
			G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, cancel, NULL);
		if (info == NULL) {
			continue;
		}
		if (g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY) {
			c->dirs_n += several;
			walk(l->data, c, cancel);
		} else {
			c->files_n += several;
			c->bytes += g_file_info_get_size(info);
		}
		g_object_unref(info);
	}
	g_task_return_boolean(task, TRUE);
}

static char *size_text(guint64 bytes) {
	char *nice = format_size(bytes);
	char *text = bytes >= 1000 ?
		g_strdup_printf("%s (%'" G_GUINT64_FORMAT " bytes)", nice, bytes) :
		g_strdup(nice);
	g_free(nice);
	return text;
}

static void counted(GObject *source, GAsyncResult *result, gpointer data) {
	struct props *p = data;
	p->counting = false;
	struct count *c = g_task_get_task_data(G_TASK(result));
	if (p->closed) {
		g_object_unref(p->cancel);
		free(p);
		return;
	}
	char *size = size_text(c->bytes);
	c8ui_label_set_text(p->size, size);
	g_free(size);
	if (p->contains) {
		char *text = g_strdup_printf("%u %s, %u %s", c->files_n,
			c->files_n == 1 ? "file" : "files", c->dirs_n,
			c->dirs_n == 1 ? "folder" : "folders");
		c8ui_label_set_text(p->contains, text);
		g_free(text);
	}
}

static void closed(void *data) {
	struct props *p = data;
	p->closed = true;
	g_cancellable_cancel(p->cancel);
	if (!p->counting) {
		g_object_unref(p->cancel);
		free(p);
	}
}

static struct c8ui_widget *row(struct c8ui_widget *grid, const char *name,
		const char *value) {
	struct c8ui_widget *n = c8ui_label_new(name, C8UI_TEXT_BODY);
	c8ui_label_set_color(n, C8UI_COLOR_SECONDARY);
	c8ui_widget_add(grid, n);
	struct c8ui_widget *v = c8ui_label_new(value ? value : "", C8UI_TEXT_BODY);
	c8ui_label_set_max_lines(v, 3);
	v->fill = true;
	c8ui_widget_add(grid, v);
	return v;
}

static void time_row(struct c8ui_widget *grid, const char *name,
		GFileInfo *info, const char *attr) {
	if (info && g_file_info_has_attribute(info, attr)) {
		char *t = format_time(g_file_info_get_attribute_uint64(info, attr));
		row(grid, name, t);
		g_free(t);
	}
}

static char *access_text(GFileInfo *info) {
	bool r = g_file_info_get_attribute_boolean(info,
		G_FILE_ATTRIBUTE_ACCESS_CAN_READ);
	bool w = g_file_info_get_attribute_boolean(info,
		G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE);
	bool x = g_file_info_get_attribute_boolean(info,
		G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE);
	bool dir = g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY;
	const char *rw = r && w ? "Read and write" : r ? "Read only" :
		w ? "Write only" : "No access";
	return g_strdup_printf("%s%s", rw, !dir && x ? ", can run as a program" :
		"");
}

void props_show(struct c8ui_root *root, const struct c8ui_rect *anchor,
		GList *files) {
	if (files == NULL) {
		return;
	}
	struct props *p = calloc(1, sizeof(*p));
	p->cancel = g_cancellable_new();
	bool one = files->next == NULL;
	GFileInfo *info = one ? g_file_query_info(files->data, "standard::*,"
		"time::*,owner::*,access::*,unix::mode", G_FILE_QUERY_INFO_NONE, NULL,
		NULL) : NULL;
	bool dir = info && g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY;

	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 16);
	box->fixed_width = 420;
	char *title;
	if (one) {
		title = info ? g_strdup(g_file_info_get_display_name(info)) :
			g_file_get_basename(files->data);
	} else {
		title = g_strdup_printf("%u items", g_list_length(files));
	}
	struct c8ui_widget *head = c8ui_label_new(c8_stealth_show(title),
		C8UI_TEXT_TITLE);
	c8ui_label_set_max_lines(head, 2);
	c8ui_widget_add(box, head);
	g_free(title);

	struct c8ui_widget *grid = c8ui_grid_new(2, 16, 8);
	c8ui_grid_set_column(grid, 1, 0, true);
	grid->fill = true;
	c8ui_widget_add(box, grid);

	/* Type, and where it is */
	const char *mime = info ? g_file_info_get_content_type(info) : NULL;
	if (one && mime) {
		char *desc = g_content_type_get_description(mime);
		char *type = dir ? g_strdup(desc) : g_strdup_printf("%s (%s)", desc,
			mime);
		row(grid, "Type", type);
		g_free(type);
		g_free(desc);
	}
	GFile *parent = g_file_get_parent(files->data);
	bool same_place = parent != NULL;
	for (GList *l = files->next; l && same_place; l = l->next) {
		GFile *pp = g_file_get_parent(l->data);
		same_place = pp && g_file_equal(pp, parent);
		g_clear_object(&pp);
	}
	if (same_place) {
		char *where = g_file_get_parse_name(parent);
		char *shown = c8_stealth_text(where);
		row(grid, "Location", shown);
		g_free(shown);
		g_free(where);
	}
	g_clear_object(&parent);

	/* Size: a file's at once, folders' once counted */
	bool count = !one || dir;
	if (count) {
		p->size = row(grid, "Size", "Counting…");
		p->contains = row(grid, "Contains", "Counting…");
	} else if (info) {
		char *size = size_text(g_file_info_get_size(info));
		row(grid, "Size", size);
		g_free(size);
	}

	if (info) {
		time_row(grid, "Created", info, G_FILE_ATTRIBUTE_TIME_CREATED);
		time_row(grid, "Modified", info, G_FILE_ATTRIBUTE_TIME_MODIFIED);
		time_row(grid, "Opened", info, G_FILE_ATTRIBUTE_TIME_ACCESS);
		const char *owner = g_file_info_get_attribute_string(info,
			G_FILE_ATTRIBUTE_OWNER_USER_REAL);
		if (owner == NULL) {
			owner = g_file_info_get_attribute_string(info,
				G_FILE_ATTRIBUTE_OWNER_USER);
		}
		if (owner) {
			row(grid, "Owner", c8_stealth_show(owner));
		}
		char *access = access_text(info);
		row(grid, "You can", access);
		g_free(access);
		if (!dir && mime) {
			GAppInfo *app = g_app_info_get_default_for_type(mime, FALSE);
			row(grid, "Opens with", app ? g_app_info_get_display_name(app) :
				"No app is set");
			g_clear_object(&app);
		}
		g_object_unref(info);
	}

	p->flyout = c8ui_flyout_show(root, anchor, box, closed, p);
	if (count) {
		struct count *c = g_new0(struct count, 1);
		for (GList *l = files; l; l = l->next) {
			c->files = g_list_append(c->files, g_object_ref(l->data));
		}
		p->counting = true;
		GTask *task = g_task_new(NULL, p->cancel, counted, p);
		g_task_set_task_data(task, c, count_free);
		g_task_run_in_thread(task, count_thread);
		g_object_unref(task);
	}
}
