/*
 * The tiles made here, kept so they can be changed later (Start keeps its
 * own copy in start.ini; this one has what Start doesn't need, such as
 * which Steam game a tile is), and the SteamGridDB key.
 */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <gio/gio.h>
#include "tiles.h"

const char *const tm_size_names[4] = { "small", "medium", "wide", "large" };

GPtrArray *tm_tiles;
char *tm_sgdb_key;

static char *ini_path(void) {
	return g_build_filename(g_get_user_config_dir(), "cont8nuum",
		"tilemaker.ini", NULL);
}

static char *picture_dir(void) {
	return g_build_filename(g_get_user_data_dir(), "cont8nuum", "tilemaker",
		NULL);
}

static void tile_free(gpointer p) {
	struct tm_tile *t = p;
	g_free(t->id);
	g_free(t->name);
	g_free(t->exec);
	g_free(t->icon);
	g_free(t->image);
	g_free(t->wide_image);
	g_free(t->steam_appid);
	g_free(t->pinned_exec);
	g_free(t);
}

static char *get(GKeyFile *kf, const char *group, const char *key) {
	char *s = g_key_file_get_string(kf, group, key, NULL);
	if (s && s[0] == '\0') {
		g_clear_pointer(&s, g_free);
	}
	return s;
}

void tm_load(void) {
	if (tm_tiles == NULL) {
		tm_tiles = g_ptr_array_new_with_free_func(tile_free);
	}
	g_ptr_array_set_size(tm_tiles, 0);
	GKeyFile *kf = g_key_file_new();
	char *path = ini_path();
	g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL);
	g_free(path);
	g_free(tm_sgdb_key);
	tm_sgdb_key = get(kf, "steamgriddb", "key");
	char **groups = g_key_file_get_groups(kf, NULL);
	for (int i = 0; groups && groups[i]; i++) {
		if (!g_str_has_prefix(groups[i], "tile ")) {
			continue;
		}
		const char *g = groups[i];
		struct tm_tile *t = g_new0(struct tm_tile, 1);
		t->id = g_strdup(g + 5);
		t->name = get(kf, g, "name");
		t->exec = get(kf, g, "exec");
		t->icon = get(kf, g, "icon");
		t->image = get(kf, g, "image");
		t->wide_image = get(kf, g, "wide_image");
		t->steam_appid = get(kf, g, "steam_appid");
		t->pinned_exec = get(kf, g, "pinned_exec");
		t->sgdb_id = g_key_file_get_integer(kf, g, "steamgriddb", NULL);
		char *color = get(kf, g, "color");
		t->color = color ? strtoul(color + (color[0] == '#'), NULL, 16) :
			0xd24726;
		g_free(color);
		char *size = get(kf, g, "size");
		t->size = TM_MEDIUM;
		for (int s = 0; size && s < 4; s++) {
			if (strcmp(size, tm_size_names[s]) == 0) {
				t->size = s;
			}
		}
		g_free(size);
		GError *e = NULL;
		t->label = g_key_file_get_boolean(kf, g, "label", &e);
		if (e) {
			t->label = true;
			g_error_free(e);
		}
		if (t->name == NULL) {
			t->name = g_strdup("Tile");
		}
		g_ptr_array_add(tm_tiles, t);
	}
	g_strfreev(groups);
	g_key_file_free(kf);
}

static void set(GKeyFile *kf, const char *group, const char *key,
		const char *value) {
	if (value && value[0]) {
		g_key_file_set_string(kf, group, key, value);
	}
}

void tm_save(void) {
	GKeyFile *kf = g_key_file_new();
	g_key_file_set_comment(kf, NULL, NULL, " Tile maker's tiles. Start "
		"keeps its own copy in start.ini.", NULL);
	set(kf, "steamgriddb", "key", tm_sgdb_key);
	for (guint i = 0; i < tm_tiles->len; i++) {
		struct tm_tile *t = tm_tiles->pdata[i];
		char *g = g_strconcat("tile ", t->id, NULL);
		set(kf, g, "name", t->name);
		set(kf, g, "exec", t->exec);
		set(kf, g, "icon", t->icon);
		set(kf, g, "image", t->image);
		set(kf, g, "wide_image", t->wide_image);
		set(kf, g, "steam_appid", t->steam_appid);
		set(kf, g, "pinned_exec", t->pinned_exec);
		if (t->sgdb_id) {
			g_key_file_set_integer(kf, g, "steamgriddb", t->sgdb_id);
		}
		char color[16];
		snprintf(color, sizeof(color), "#%06x", t->color & 0xffffff);
		set(kf, g, "color", color);
		set(kf, g, "size", tm_size_names[t->size]);
		g_key_file_set_boolean(kf, g, "label", t->label);
		g_free(g);
	}
	char *path = ini_path();
	char *dir = g_path_get_dirname(path);
	g_mkdir_with_parents(dir, 0700);
	gsize len;
	char *text = g_key_file_to_data(kf, &len, NULL);
	/* The key is someone's: only ours to read */
	GError *e = NULL;
	if (!g_file_set_contents_full(path, text, len,
			G_FILE_SET_CONTENTS_CONSISTENT, 0600, &e)) {
		fprintf(stderr, "c8-tiles: %s\n", e->message);
		g_error_free(e);
	}
	g_free(text);
	g_free(dir);
	g_free(path);
	g_key_file_free(kf);
}

struct tm_tile *tm_tile_new(void) {
	struct tm_tile *t = g_new0(struct tm_tile, 1);
	char hex[9];
	do {
		snprintf(hex, sizeof(hex), "%08x", g_random_int());
		g_free(t->id);
		t->id = g_strconcat(APP_ID ".", hex, NULL);
	} while (tm_tile_find(t->id));
	t->name = g_strdup("");
	t->color = 0xd24726;
	t->size = TM_MEDIUM;
	t->label = true;
	g_ptr_array_add(tm_tiles, t);
	return t;
}

struct tm_tile *tm_tile_find(const char *id) {
	for (guint i = 0; id && tm_tiles && i < tm_tiles->len; i++) {
		struct tm_tile *t = tm_tiles->pdata[i];
		if (strcmp(t->id, id) == 0) {
			return t;
		}
	}
	return NULL;
}

void tm_tile_delete(struct tm_tile *t) {
	g_ptr_array_remove(tm_tiles, t);
	tm_pictures_prune();
}

char *tm_picture_path(struct tm_tile *t, const char *kind, const char *ext) {
	char *dir = picture_dir();
	g_mkdir_with_parents(dir, 0700);
	const char *dot = strrchr(t->id, '.');
	char *name = g_strdup_printf("%s-%s-%" G_GINT64_FORMAT "%s",
		dot ? dot + 1 : t->id, kind, g_get_real_time() / 1000, ext);
	char *path = g_build_filename(dir, name, NULL);
	g_free(name);
	g_free(dir);
	return path;
}

static const char *ext_of(const char *path) {
	const char *slash = strrchr(path, '/');
	const char *dot = strrchr(slash ? slash : path, '.');
	if (dot && (g_ascii_strcasecmp(dot, ".png") == 0 ||
			g_ascii_strcasecmp(dot, ".jpg") == 0 ||
			g_ascii_strcasecmp(dot, ".jpeg") == 0 ||
			g_ascii_strcasecmp(dot, ".svg") == 0)) {
		return dot;
	}
	return ".png";
}

char *tm_picture_import(struct tm_tile *t, const char *kind,
		const char *path) {
	char *dest = tm_picture_path(t, kind, ext_of(path));
	GFile *from = g_file_new_for_path(path), *to = g_file_new_for_path(dest);
	bool ok = g_file_copy(from, to, G_FILE_COPY_OVERWRITE, NULL, NULL, NULL,
		NULL);
	g_object_unref(from);
	g_object_unref(to);
	if (!ok) {
		g_clear_pointer(&dest, g_free);
	}
	return dest;
}

static bool in_use(const char *path) {
	for (guint i = 0; i < tm_tiles->len; i++) {
		struct tm_tile *t = tm_tiles->pdata[i];
		if (g_strcmp0(t->image, path) == 0 ||
				g_strcmp0(t->wide_image, path) == 0 ||
				g_strcmp0(t->icon, path) == 0) {
			return true;
		}
	}
	return false;
}

void tm_pictures_prune(void) {
	char *dir = picture_dir();
	GDir *d = g_dir_open(dir, 0, NULL);
	const char *name;
	while (d && (name = g_dir_read_name(d))) {
		char *path = g_build_filename(dir, name, NULL);
		if (!in_use(path)) {
			g_unlink(path);
		}
		g_free(path);
	}
	if (d) {
		g_dir_close(d);
	}
	g_free(dir);
}

const char *tm_key(void) {
	const char *env = g_getenv("STEAMGRIDDB_API_KEY");
	if (env && env[0]) {
		return env;
	}
	return tm_sgdb_key && tm_sgdb_key[0] ? tm_sgdb_key : NULL;
}
