/*
 * c8-photos-tile: Photos' live tile, as Windows 8's: the newest pictures
 * in Pictures (and the folders in it) taking turns on the tile. Start
 * runs it (c8-photos.widget's Provider=) when the tile is pinned and at
 * login; it needs no Wayland. It looks again when something in Pictures
 * changes and every few minutes; each picture shown is made small first
 * (a JPEG in the cache, decoded and encoded by glycin in its sandbox),
 * since Start would otherwise read whole photos to draw a tile. It sends
 * to the tile it was started for and to the app's own tile, so Photos
 * pinned from All apps comes alive too while this runs.
 */
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <glib/gstdio.h>
#include <glycin.h>
#include "encode.h"
#include "tiles.h"

#define APP_TILE "org.cont8nuum.Photos"
#define SHOWN 5 // the shell rotates up to five
#define SMALL_SIDE 640 // a large tile at twice the scale
#define DEPTH 6
#define MOST_FILES 20000 // looked at, at most, in one go
#define LOOK_EVERY_S (10 * 60)
#define SETTLE_S 5 // pictures copied in come in a burst: once it stops

static GMainLoop *loop;
static const char *tile_id;
static guint settle_timer;
static GFileMonitor *monitor;
static bool looking, again;
static char *last_sent; // what the tile has, so the same isn't sent again

struct found {
	char *path;
	guint64 mtime;
};

static void found_free(gpointer p) {
	struct found *f = p;
	g_free(f->path);
	g_free(f);
}

static GHashTable *picture_types(void) {
	static GHashTable *types;
	if (types == NULL) {
		types = 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(types, g_strdup(list[i]));
		}
		g_strfreev(list);
	}
	return types;
}

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

/* Keeps the newest SHOWN of what is under dir */
static void walk(GFile *dir, int depth, GPtrArray *newest, int *seen) {
	GFileEnumerator *en = g_file_enumerate_children(dir, ATTRS,
		G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, NULL);
	if (en == NULL) {
		return;
	}
	GFileInfo *info;
	GFile *child;
	while (*seen < MOST_FILES &&
			g_file_enumerator_iterate(en, &info, &child, NULL, 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 < DEPTH) {
				walk(child, depth + 1, newest, seen);
			}
			continue;
		}
		const char *type = g_file_info_get_attribute_string(info,
			G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE);
		char *mime = type ? g_content_type_get_mime_type(type) : NULL;
		bool picture = mime && g_hash_table_contains(picture_types(), mime) &&
			!g_str_has_prefix(mime, "image/svg"); // drawings, not photos
		g_free(mime);
		if (!picture) {
			continue;
		}
		guint64 mtime = g_file_info_get_attribute_uint64(info,
			G_FILE_ATTRIBUTE_TIME_MODIFIED);
		guint at = newest->len;
		while (at > 0 &&
				((struct found *)newest->pdata[at - 1])->mtime < mtime) {
			at--;
		}
		if (at >= SHOWN) {
			continue;
		}
		struct found *f = g_new0(struct found, 1);
		f->path = g_file_get_path(child);
		f->mtime = mtime;
		g_ptr_array_insert(newest, at, f);
		if (newest->len > SHOWN) {
			g_ptr_array_remove_index(newest, newest->len - 1);
		}
	}
	g_object_unref(en);
}

static char *cache_dir(void) {
	return g_build_filename(g_get_user_cache_dir(), "cont8nuum", "photos-tile",
		NULL);
}

/* A small copy for the tile, made once per picture and change */
static char *small_copy(const struct found *f) {
	char *key = g_strdup_printf("%s %" G_GUINT64_FORMAT, f->path, f->mtime);
	char *sum = g_compute_checksum_for_string(G_CHECKSUM_MD5, key, -1);
	char *dir = cache_dir();
	char *name = g_strdup_printf("%s.jpg", sum);
	char *out = g_build_filename(dir, name, NULL);
	g_free(name);
	g_free(dir);
	g_free(sum);
	g_free(key);
	if (g_file_test(out, G_FILE_TEST_EXISTS)) {
		return out;
	}
	GError *err = NULL;
	cairo_surface_t *s = ph_decode(f->path, &err);
	GBytes *bytes = NULL;
	if (s) {
		cairo_surface_t *small = ph_shrink(s, SMALL_SIDE);
		cairo_surface_destroy(s);
		bytes = ph_encode(small, "image/jpeg", &err);
		cairo_surface_destroy(small);
	}
	if (bytes) {
		gsize len;
		const char *b = g_bytes_get_data(bytes, &len);
		g_file_set_contents(out, b, len, &err);
		g_bytes_unref(bytes);
	}
	if (err) {
		g_message("%s: %s", f->path, err->message);
		g_error_free(err);
		g_clear_pointer(&out, g_free);
	}
	return out;
}

/* On a thread: the newest pictures, made small; their paths */
static void look_thread(GTask *task, gpointer src, gpointer data,
		GCancellable *cancel) {
	picture_types();
	GPtrArray *newest = g_ptr_array_new_with_free_func(found_free);
	const char *pics = g_get_user_special_dir(G_USER_DIRECTORY_PICTURES);
	if (pics && g_file_test(pics, G_FILE_TEST_IS_DIR)) {
		GFile *dir = g_file_new_for_path(pics);
		int seen = 0;
		walk(dir, 0, newest, &seen);
		g_object_unref(dir);
	}
	char *cdir = cache_dir();
	g_mkdir_with_parents(cdir, 0700);
	GPtrArray *small = g_ptr_array_new_with_free_func(g_free);
	for (guint i = 0; i < newest->len; i++) {
		char *path = small_copy(newest->pdata[i]);
		if (path) {
			g_ptr_array_add(small, path);
		}
	}
	/* Copies of pictures no longer shown go, unless the tile may still
	 * show them (sent before, until the new ones are) */
	GDir *d = g_dir_open(cdir, 0, NULL);
	const char *name;
	while (d && (name = g_dir_read_name(d))) {
		char *path = g_build_filename(cdir, name, NULL);
		bool keep = false;
		for (guint i = 0; i < small->len && !keep; i++) {
			keep = strcmp(small->pdata[i], path) == 0;
		}
		keep = keep || (last_sent && strstr(last_sent, path));
		if (!keep) {
			g_unlink(path);
		}
		g_free(path);
	}
	if (d) {
		g_dir_close(d);
	}
	g_free(cdir);
	g_ptr_array_unref(newest);
	g_task_return_pointer(task, small, (GDestroyNotify)g_ptr_array_unref);
}

static void send_to(const char *tile, GPtrArray *small) {
	c8_tiles_call("Clear", g_variant_new("(s)", tile));
	for (guint i = 0; i < small->len; i++) {
		GVariantBuilder b;
		g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
		g_variant_builder_add(&b, "{ss}", "template", "image");
		g_variant_builder_add(&b, "{ss}", "image",
			(const char *)small->pdata[i]);
		char tag[16];
		snprintf(tag, sizeof(tag), "p%u", i);
		c8_tiles_call("Update", g_variant_new("(ss@a{ss})", tile, tag,
			g_variant_builder_end(&b)));
	}
}

static void look(void);

static void looked(GObject *src, GAsyncResult *res, gpointer data) {
	GPtrArray *small = g_task_propagate_pointer(G_TASK(res), NULL);
	looking = false;
	GString *all = g_string_new(NULL);
	for (guint i = 0; small && i < small->len; i++) {
		g_string_append_printf(all, "%s\n", (char *)small->pdata[i]);
	}
	if (small && (last_sent == NULL || strcmp(last_sent, all->str) != 0)) {
		send_to(tile_id, small);
		if (strcmp(tile_id, APP_TILE) != 0) {
			send_to(APP_TILE, small);
		}
		g_free(last_sent);
		last_sent = g_strdup(all->str);
	}
	g_string_free(all, TRUE);
	if (small) {
		g_ptr_array_unref(small);
	}
	if (again) {
		again = false;
		look();
	}
}

static void look(void) {
	if (looking) {
		again = true;
		return;
	}
	looking = true;
	GTask *task = g_task_new(NULL, NULL, looked, NULL);
	g_task_run_in_thread(task, look_thread);
	g_object_unref(task);
}

static gboolean settled(gpointer data) {
	settle_timer = 0;
	look();
	return G_SOURCE_REMOVE;
}

static void look_soon(void) {
	if (settle_timer) {
		g_source_remove(settle_timer);
	}
	settle_timer = g_timeout_add_seconds(SETTLE_S, settled, NULL);
}

static gboolean every_while(gpointer data) {
	look();
	return G_SOURCE_CONTINUE;
}

/* Only Pictures itself is watched (a watch per folder costs inotify
 * watches); what changes deeper is found by the regular look */
static void pictures_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_ATTRIBUTE_CHANGED) {
		look_soon();
	}
}

static void shell_here(void *data) {
	/* A fresh shell may have lost what was sent */
	g_clear_pointer(&last_sent, g_free);
	look();
}

static void leave(void *data) {
	g_main_loop_quit(loop);
}

static struct c8_tile_provider provider = {
	.quit = leave,
	.quit_unpinned = true,
	.shell = shell_here,
};

int main(int argc, char **argv) {
	setlocale(LC_ALL, "");
	if (argc != 2) {
		fprintf(stderr, "Usage: c8-photos-tile TILE-ID\n");
		return 2;
	}
	tile_id = argv[1];
	loop = g_main_loop_new(NULL, FALSE);
	const char *pics = g_get_user_special_dir(G_USER_DIRECTORY_PICTURES);
	if (pics) {
		GFile *dir = g_file_new_for_path(pics);
		monitor = g_file_monitor_directory(dir, G_FILE_MONITOR_WATCH_MOVES,
			NULL, NULL);
		g_object_unref(dir);
		if (monitor) {
			g_signal_connect(monitor, "changed",
				G_CALLBACK(pictures_changed), NULL);
		}
	}
	provider.tile_id = tile_id;
	c8_tile_provider_watch(&provider, NULL);
	look();
	g_timeout_add_seconds(LOOK_EVERY_S, every_while, NULL);
	g_main_loop_run(loop);
	return 0;
}
