/*
 * c8-news-tile: keeps the News live tile fresh while the app isn't open.
 * Start runs it (news.widget's Provider=) when the tile is pinned and at
 * login; it needs no Wayland. It reads the feeds the app has, every
 * [news] interval minutes (an rssnail account's, when PC settings has
 * one), and quits when told the tile restarts or when
 * the shell has been gone a minute.
 */
#include <gio/gio.h>
#include <glib-unix.h>
#include <signal.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include "tiles.h"
#include "news.h"


static GMainLoop *loop;
static const char *tile_id;
static guint image_timer;
static int pending;

static gboolean push(gpointer data) {
	image_timer = 0;
	news_tile_update(tile_id);
	return G_SOURCE_REMOVE;
}

/* Pictures arrive after the text: send the tile again once they settle */
static void image_ready(const char *url, void *data) {
	if (image_timer) {
		g_source_remove(image_timer);
	}
	image_timer = g_timeout_add_seconds(3, push, NULL);
}

static void feed_done(struct feed *feed, bool changed, void *data) {
	if (--pending == 0) {
		push(NULL);
	}
}

/* pending: the feeds being read; the tile goes when the last is in */
static void refresh_feeds(void) {
	pending = 0;
	for (guint i = 0; i < news_feeds->len; i++) {
		pending += ((struct feed *)news_feeds->pdata[i])->loading;
	}
	for (guint i = 0; i < news_feeds->len; i++) {
		struct feed *f = news_feeds->pdata[i];
		if (!f->loading) {
			pending++;
			feed_refresh(f, feed_done, NULL);
		}
	}
}

static gboolean refresh(gpointer data) {
	rssnail_sync();
	refresh_feeds();
	return G_SOURCE_CONTINUE;
}

/* rssnail's feeds came, went or changed: read them */
static void remote_changed(const char *error, bool loud, void *data) {
	if (error) {
		g_message("%s", error);
		return;
	}
	for (guint i = 0; i < news_feeds->len; i++) {
		struct feed *f = news_feeds->pdata[i];
		if (f->stories->len == 0) {
			feed_load_cache(f);
		}
	}
	push(NULL);
	refresh_feeds();
}

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

static struct c8_tile_provider provider = { .quit = leave };

int main(int argc, char **argv) {
	setlocale(LC_ALL, "");
	if (argc != 2) {
		fprintf(stderr, "Usage: c8-news-tile TILE-ID\n");
		return 2;
	}
	tile_id = argv[1];
	news_load();
	rssnail_init(remote_changed, NULL, false);
	for (guint i = 0; i < news_feeds->len; i++) {
		feed_load_cache(news_feeds->pdata[i]);
	}
	loop = g_main_loop_new(NULL, FALSE);
	news_image_on_ready(image_ready, NULL);

	provider.tile_id = tile_id;
	c8_tile_provider_watch(&provider, NULL);
	push(NULL); // what the cache has, at once
	refresh(NULL);
	g_timeout_add_seconds(news_settings.interval * 60, refresh, NULL);
	g_main_loop_run(loop);
	return 0;
}
