/*
 * The app's own tile on Start (pinned from All apps it is named by our
 * desktop file id): what was watched last, its picture where it was
 * left, and how much of it is left, as Windows 8's Video tile had.
 *
 * Sent by the app itself when it lets a video go; no provider runs. The
 * shell reads pictures from files, so the frame goes in our cache, in
 * one of two files taken in turns: the one the tile shows now stays
 * until the next has replaced it.
 */
#include <math.h>
#include <glib/gstdio.h>
#include "tiles.h"
#include "video.h"

#define TILE_W 480

static int slot; // the file to write next

static char *picture_path(int which) {
	char name[16];
	g_snprintf(name, sizeof(name), "last-%d.png", which);
	return g_build_filename(g_get_user_cache_dir(), "cont8nuum",
		"video-tile", name, NULL);
}

static char *time_left(double position, double duration) {
	if (duration <= 0) {
		return g_strdup("Carry on watching");
	}
	double left = duration - position;
	/* As player.c's END_S: where it wouldn't carry on from */
	if (left < 10) {
		return g_strdup("Watched");
	}
	int minutes = (int)ceil(left / 60);
	if (minutes < 60) {
		return g_strdup_printf(minutes == 1 ? "%d minute left" :
			"%d minutes left", minutes);
	}
	return g_strdup_printf("%d h %02d min left", minutes / 60, minutes % 60);
}

void tile_left(const char *name, double position, double duration) {
	if (!prefs.tile || name == NULL) {
		return;
	}
	char *file = picture_path(slot);
	char *dir = g_path_get_dirname(file);
	g_mkdir_with_parents(dir, 0700);
	bool picture = player_snapshot(file, TILE_W);
	char *left = time_left(position, duration);
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
	g_variant_builder_add(&b, "{ss}", "template", picture ? "peek" : "text");
	if (picture) {
		g_variant_builder_add(&b, "{ss}", "image", file);
	}
	g_variant_builder_add(&b, "{ss}", "heading", name);
	g_variant_builder_add(&b, "{ss}", "text1", left);
	/* Untagged: it replaces what was there */
	c8_tiles_call("Update", g_variant_new("(ss@a{ss})", APP_ID, "",
		g_variant_builder_end(&b)));
	if (picture) {
		slot = !slot;
	}
	g_free(left);
	g_free(dir);
	g_free(file);
}

void tile_clear(void) {
	c8_tiles_call("Clear", g_variant_new("(s)", APP_ID));
	for (int i = 0; i < 2; i++) {
		char *file = picture_path(i);
		g_unlink(file);
		g_free(file);
	}
}

void tile_flush(void) {
	GDBusConnection *bus = c8_tiles_bus();
	if (bus) {
		g_dbus_connection_flush_sync(bus, NULL, NULL);
	}
}
