/*
 * The live tile, over org.cont8nuum.Tiles1: the newest posts of the
 * Following timeline as tagged updates Start rotates through (a post's
 * picture sliding up to its words, or its author's picture beside them),
 * and the notifications not yet seen as the badge.
 */
#include <gio/gio.h>
#include <string.h>
#include "tiles.h"
#include "sky.h"

#define POSTS 5

void sky_tile_clear(const char *tile) {
	c8_tiles_call("Clear", g_variant_new("(s)", tile));
}

void sky_tile_update(const char *tile, GPtrArray *items, int unread) {
	guint shown = 0;
	for (guint i = 0; items && i < items->len && shown < POSTS; i++) {
		struct sky_item *it = items->pdata[i];
		struct sky_post *p = it->post;
		if (it->kind != SKY_ITEM_POST || p == NULL ||
				(p->text == NULL && p->n_images == 0)) {
			continue;
		}
		GVariantBuilder b;
		g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
		const char *picture = sky_settings.images && p->n_images &&
			!p->sensitive ? p->images[0].thumb : NULL;
		const char *image = sky_image_path(picture);
		if (picture && !image) {
			sky_image_fetch(picture); // for the next time
		}
		/* In stealth mode, our own posts with the persona's name and no
		 * picture of us */
		const char *face = sky_shown_avatar(p->did, p->avatar);
		const char *avatar = sky_image_path(face);
		if (face && !avatar) {
			sky_image_fetch(face);
		}
		g_variant_builder_add(&b, "{ss}", "heading",
			sky_shown_name(p->did, p->name));
		if (p->text) {
			g_variant_builder_add(&b, "{ss}", "text1", sky_shown_text(p->text));
		}
		if (image) {
			g_variant_builder_add(&b, "{ss}", "image", image);
			g_variant_builder_add(&b, "{ss}", "template", "peek");
		} else if (avatar) {
			g_variant_builder_add(&b, "{ss}", "image", avatar);
			g_variant_builder_add(&b, "{ss}", "template", "imagetext");
		} else {
			g_variant_builder_add(&b, "{ss}", "template", "text");
		}
		char *tag = g_strdup_printf("p%u", shown++);
		c8_tiles_call("Update", g_variant_new("(ssa{ss})", tile, tag, &b));
		g_free(tag);
	}
	for (guint i = shown; i < POSTS; i++) {
		char *tag = g_strdup_printf("p%u", i);
		c8_tiles_call("Remove", g_variant_new("(ss)", tile, tag));
		g_free(tag);
	}
	char badge[16] = "";
	if (unread > 0) {
		g_snprintf(badge, sizeof(badge), "%d", unread > 99 ? 99 : unread);
	}
	c8_tiles_call("SetBadge", g_variant_new("(ss)", tile, badge));
}
