/*
 * c8-cirrus-tile: keeps Cirrus's live tile fresh while the app isn't
 * open, and tells of new notifications. Start runs it (the widget's
 * Provider=) when the tile is pinned and at login; it needs no Wayland.
 * Every five minutes it reads the newest posts of Following and how many
 * notifications wait, and shows a toast for each that came since it last
 * looked (three at most, then how many more). It quits when told the
 * tile restarts, when it's unpinned, or when the shell has been gone a
 * minute.
 */
#include <gio/gio.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include "stealth.h"
#include "tiles.h"
#include "sky.h"

#define REFRESH_S (5 * 60)
#define SETTLE_S 4 // pictures come one by one: send the tile once they stop
#define TOASTS_MAX 3

static GMainLoop *loop;
static const char *tile_id;
static GPtrArray *items; // the newest posts
static int unread;
static guint push_timer;
static int64_t last_round;
static int64_t toasted; // the newest notification told of, unix seconds

static gboolean push(gpointer data) {
	push_timer = 0;
	if (sky_me == NULL) {
		sky_tile_clear(APP_ID);
		sky_tile_clear(tile_id);
		return G_SOURCE_REMOVE;
	}
	if (items) {
		sky_tile_update(APP_ID, items, unread);
		sky_tile_update(tile_id, items, unread);
	}
	return G_SOURCE_REMOVE;
}

static void push_later(void) {
	if (push_timer) {
		g_source_remove(push_timer);
	}
	push_timer = g_timeout_add_seconds(SETTLE_S, push, NULL);
}

static void image_ready(const char *url, void *data) {
	push_later();
}

/* Toasts */

static char *toasted_path(void) {
	char *name = g_strdup_printf("toasted-%s", sky_me ? sky_me->did : "none");
	g_strdelimit(name, ":/", '-');
	char *path = sky_state_path(name);
	g_free(name);
	return path;
}

static void toasted_load(void) {
	char *path = toasted_path(), *text = NULL;
	toasted = 0;
	if (g_file_get_contents(path, &text, NULL, NULL)) {
		toasted = g_ascii_strtoll(text, NULL, 10);
		g_free(text);
	}
	g_free(path);
}

static void toasted_save(void) {
	char *path = toasted_path();
	char *dir = g_path_get_dirname(path);
	char *text = g_strdup_printf("%" G_GINT64_FORMAT "\n", toasted);
	g_mkdir_with_parents(dir, 0700);
	g_file_set_contents(path, text, -1, NULL);
	g_free(text);
	g_free(dir);
	g_free(path);
}

static void toast(const char *summary, const char *body) {
	GDBusConnection *bus = c8_tiles_bus();
	if (bus == NULL) {
		return;
	}
	GVariantBuilder hints;
	g_variant_builder_init(&hints, G_VARIANT_TYPE("a{sv}"));
	g_variant_builder_add(&hints, "{sv}", "desktop-entry",
		g_variant_new_string(APP_ID));
	g_dbus_connection_call(bus, "org.freedesktop.Notifications",
		"/org/freedesktop/Notifications", "org.freedesktop.Notifications",
		"Notify", g_variant_new("(susssasa{sv}i)", "Cirrus", 0, APP_ID,
			summary, body ? body : "", NULL, &hints, -1),
		NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
}

static void got_notices(int status, struct json *json, const char *error,
		void *data) {
	if (status != 200) {
		return;
	}
	GPtrArray *notices = g_ptr_array_new_with_free_func(sky_item_free);
	GPtrArray *need = g_ptr_array_new_with_free_func(g_free);
	sky_parse_notices(json, notices, need);
	int64_t newest = toasted;
	int told = 0, more = 0;
	/* Oldest first, as they happened */
	for (int i = (int)notices->len - 1; i >= 0; i--) {
		struct sky_item *it = notices->pdata[i];
		if (!it->unread || it->date <= toasted) {
			continue;
		}
		newest = it->date > newest ? it->date : newest;
		if (told == TOASTS_MAX) {
			more++;
			continue;
		}
		char *summary = g_strdup_printf("%s %s", sky_shown_name(it->did,
			it->name), it->reason);
		toast(summary, sky_shown_text(it->text ? it->text :
			it->post ? it->post->text : NULL));
		g_free(summary);
		told++;
	}
	if (more) {
		char *summary = g_strdup_printf(more == 1 ? "And %d more notification" :
			"And %d more notifications", more);
		toast(summary, NULL);
		g_free(summary);
	}
	if (newest != toasted) {
		toasted = newest;
		toasted_save();
	}
	g_ptr_array_unref(notices);
	g_ptr_array_unref(need);
}

static void got_unread(int status, struct json *json, const char *error,
		void *data) {
	if (status != 200) {
		return;
	}
	int count = (int)json_num(json_get(json, "count"), 0);
	bool more = count > unread;
	unread = count;
	push_later();
	if (toasted == 0) {
		/* The first time: what waits already isn't news */
		toasted = g_get_real_time() / G_USEC_PER_SEC;
		toasted_save();
	} else if (more && sky_settings.toasts) {
		sky_get("app.bsky.notification.listNotifications?limit=20",
			got_notices, NULL);
	}
}

static void got_timeline(int status, struct json *json, const char *error,
		void *data) {
	if (status != 200) {
		if (error) {
			g_message("%s", error);
		}
		return;
	}
	if (items) {
		g_ptr_array_unref(items);
	}
	items = g_ptr_array_new_with_free_func(sky_item_free);
	sky_parse_feed(json, items);
	push(NULL); // starts the pictures coming
	push_later();
}

static gboolean refresh(gpointer data) {
	/* The app may have signed in, out or changed accounts meanwhile */
	char *was = g_strdup(sky_me ? sky_me->did : "");
	sky_load();
	sky_generation++;
	if (g_strcmp0(was, sky_me ? sky_me->did : "") != 0) {
		g_clear_pointer(&items, g_ptr_array_unref);
		unread = 0;
		toasted_load();
		push(NULL);
	}
	g_free(was);
	last_round = g_get_monotonic_time();
	if (sky_me) {
		sky_get("app.bsky.feed.getTimeline?limit=15", got_timeline, NULL);
		sky_get("app.bsky.notification.getUnreadCount", got_unread, NULL);
	}
	return G_SOURCE_CONTINUE;
}

static void shell_here(void *data) {
	push(NULL); // a fresh shell may have lost what we sent
}

/* Start came up: what it shows shouldn't be minutes old */
static void visible(bool shown, void *data) {
	if (shown && g_get_monotonic_time() - last_round > 60 * G_USEC_PER_SEC) {
		refresh(NULL);
	}
}

/* Stealth mode went on or off: the tile with or without us */
static void stealth_changed(void *data) {
	push(NULL);
}

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

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

int main(int argc, char **argv) {
	setlocale(LC_ALL, "");
	if (argc != 2) {
		fprintf(stderr, "Usage: c8-cirrus-tile TILE-ID\n");
		return 2;
	}
	tile_id = argv[1];
	loop = g_main_loop_new(NULL, FALSE);
	sky_load();
	toasted_load();
	sky_image_on_ready(image_ready, NULL);
	provider.tile_id = tile_id;
	c8_tile_provider_watch(&provider, NULL);
	c8_stealth_watch(stealth_changed, NULL);
	refresh(NULL);
	g_timeout_add_seconds(REFRESH_S, refresh, NULL);
	g_main_loop_run(loop);
	return 0;
}
