/*
 * c8-weather-tile: keeps Weather's live tiles fresh while the app isn't
 * open. Start runs it (c8-weather.widget's Provider=) when the tile is
 * pinned and at login; it needs no Wayland. Every quarter of an hour it
 * reads the forecasts again and sends the default place to the app's
 * tile and the widget's, and each place pinned on its own to its tile. 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 <glib-unix.h>
#include <locale.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include "stealth.h"
#include "tiles.h"
#include "weather.h"

#define REFRESH_S (15 * 60)
#define SETTLE_S 3 // answers come one by one: send the tiles once they stop

static GMainLoop *loop;
static const char *tile_id;
static guint push_timer;

static gboolean push(gpointer data) {
	push_timer = 0;
	ws_tiles_update();
	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 changed(struct ws_place *place, void *data) {
	push_later();
}

static gboolean refresh(gpointer data) {
	ws_account_sync();
	ws_refresh_all();
	return G_SOURCE_CONTINUE;
}

/* The account's places came, went or changed */
static void remote_changed(const char *error, bool loud, void *data) {
	if (error) {
		g_message("%s", error);
		return;
	}
	for (guint i = 0; i < ws_places->len; i++) {
		struct ws_place *p = ws_places->pdata[i];
		if (p->forecast == NULL) {
			ws_load_cached(p);
		}
	}
	push(NULL);
	ws_refresh_all();
}

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

/* Stealth mode on or off: the place's name on the tiles changes */
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,
};

int main(int argc, char **argv) {
	setlocale(LC_ALL, "");
	if (argc != 2) {
		fprintf(stderr, "Usage: c8-weather-tile TILE-ID\n");
		return 2;
	}
	tile_id = argv[1];
	loop = g_main_loop_new(NULL, FALSE);

	ws_load();
	ws_account_init(remote_changed, NULL, false);
	for (guint i = 0; i < ws_places->len; i++) {
		ws_load_cached(ws_places->pdata[i]);
	}
	ws_on_change(changed, NULL);
	c8_stealth_watch(stealth_changed, 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(REFRESH_S, refresh, NULL);
	g_main_loop_run(loop);
	return 0;
}
