/*
 * SteamGridDB (https://www.steamgriddb.com/api/v2): games by name or by
 * Steam app id, then their art. Wide grids (460x215, 920x430) are a wide
 * tile's shape, square ones (512x512, 1024x1024) a medium or large one's;
 * icons go on small tiles. Each user brings their own API key, from their
 * SteamGridDB preferences page.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include "json.h"
#include "tiles.h"

#define API "https://www.steamgriddb.com/api/v2"

void tm_sgdb_game_free(gpointer p) {
	struct tm_sgdb_game *g = p;
	if (g == NULL) {
		return; // moved out by the caller
	}
	g_free(g->name);
	g_free(g);
}

void tm_art_item_free(gpointer p) {
	struct tm_art_item *a = p;
	if (a == NULL) {
		return; // moved out by the caller
	}
	g_free(a->url);
	g_free(a->thumb);
	g_free(a->author);
	g_free(a);
}

static char *auth(void) {
	const char *key = tm_key();
	return key ? g_strconcat(key, NULL) : NULL;
}

/* Why it didn't answer, in words */
static char *failure(int status, struct json *j) {
	if (status == 0) {
		return g_strdup("SteamGridDB didn't answer. Check the connection.");
	}
	if (status == 401) {
		return g_strdup("SteamGridDB didn't take the API key. Check it in "
			"Settings.");
	}
	if (status == 404) {
		return g_strdup("SteamGridDB doesn't know this game.");
	}
	struct json *errors = json_get(j, "errors");
	const char *why = json_str(json_at(errors, 0), NULL);
	return why ? g_strdup_printf("SteamGridDB said: %s", why) :
		g_strdup_printf("SteamGridDB answered %d.", status);
}

struct games_call {
	tm_sgdb_games_fn fn;
	void *data;
	bool one; // /games/steam answers one object, not a list
};

static struct tm_sgdb_game *game_of(struct json *j) {
	int id = (int)json_num(json_get(j, "id"), 0);
	const char *name = json_str(json_get(j, "name"), NULL);
	if (id <= 0 || name == NULL) {
		return NULL;
	}
	struct tm_sgdb_game *g = g_new0(struct tm_sgdb_game, 1);
	g->id = id;
	g->name = g_strdup(name);
	double when = json_num(json_get(j, "release_date"), 0);
	if (when > 0) {
		GDateTime *dt = g_date_time_new_from_unix_utc((gint64)when);
		g->year = dt ? g_date_time_get_year(dt) : 0;
		if (dt) {
			g_date_time_unref(dt);
		}
	}
	return g;
}

static void games_got(int status, const char *body, void *data) {
	struct games_call *c = data;
	struct json *j = body ? json_parse(body) : NULL;
	GPtrArray *list = g_ptr_array_new_with_free_func(tm_sgdb_game_free);
	char *error = NULL;
	if (status == 200 && json_bool(json_get(j, "success"))) {
		struct json *d = json_get(j, "data");
		if (c->one) {
			struct tm_sgdb_game *g = game_of(d);
			if (g) {
				g_ptr_array_add(list, g);
			}
		} else {
			for (int i = 0; i < json_length(d); i++) {
				struct tm_sgdb_game *g = game_of(json_at(d, i));
				if (g) {
					g_ptr_array_add(list, g);
				}
			}
		}
	} else {
		error = failure(status, j);
	}
	c->fn(list, error, c->data);
	g_ptr_array_unref(list);
	g_free(error);
	json_free(j);
	g_free(c);
}

static void games_call(const char *url, bool one, tm_sgdb_games_fn fn,
		void *data) {
	if (tm_key() == NULL) {
		GPtrArray *none = g_ptr_array_new();
		fn(none, "Add your SteamGridDB API key in Settings first.", data);
		g_ptr_array_unref(none);
		return;
	}
	struct games_call *c = g_new0(struct games_call, 1);
	c->fn = fn;
	c->data = data;
	c->one = one;
	char *a = auth();
	tm_http_get(url, a, games_got, c);
	g_free(a);
}

void tm_sgdb_search(const char *term, tm_sgdb_games_fn fn, void *data) {
	char *esc = g_uri_escape_string(term, NULL, FALSE);
	char *url = g_strdup_printf(API "/search/autocomplete/%s", esc);
	games_call(url, false, fn, data);
	g_free(url);
	g_free(esc);
}

void tm_sgdb_steam(const char *appid, tm_sgdb_games_fn fn, void *data) {
	char *esc = g_uri_escape_string(appid, NULL, FALSE);
	char *url = g_strdup_printf(API "/games/steam/%s", esc);
	games_call(url, true, fn, data);
	g_free(url);
	g_free(esc);
}

struct art_call {
	enum tm_art kind;
	tm_sgdb_art_fn fn;
	void *data;
};

static void art_got(int status, const char *body, void *data) {
	struct art_call *c = data;
	struct json *j = body ? json_parse(body) : NULL;
	GPtrArray *list = g_ptr_array_new_with_free_func(tm_art_item_free);
	char *error = NULL;
	if (status == 200 && json_bool(json_get(j, "success"))) {
		struct json *d = json_get(j, "data");
		for (int i = 0; i < json_length(d); i++) {
			struct json *a = json_at(d, i);
			const char *url = json_str(json_get(a, "url"), NULL);
			if (url == NULL || !g_str_has_prefix(url, "https://")) {
				continue;
			}
			struct tm_art_item *item = g_new0(struct tm_art_item, 1);
			item->url = g_strdup(url);
			const char *thumb = json_str(json_get(a, "thumb"), NULL);
			item->thumb = g_strdup(thumb && g_str_has_prefix(thumb,
				"https://") ? thumb : url);
			item->author = g_strdup(json_str(json_get(json_get(a, "author"),
				"name"), NULL));
			item->width = (int)json_num(json_get(a, "width"), 0);
			item->height = (int)json_num(json_get(a, "height"), 0);
			g_ptr_array_add(list, item);
		}
	} else {
		error = failure(status, j);
	}
	c->fn(c->kind, list, error, c->data);
	g_ptr_array_unref(list);
	g_free(error);
	json_free(j);
	g_free(c);
}

void tm_sgdb_art(int game, enum tm_art kind, tm_sgdb_art_fn fn, void *data) {
	static const char *const paths[TM_ART_COUNT] = {
		/* PNG and JPEG only: Start decodes with gdk-pixbuf, which may
		 * not have WebP */
		[TM_ART_WIDE] = "grids/game/%d?dimensions=460x215,920x430"
			"&mimes=image/png,image/jpeg&types=static",
		[TM_ART_SQUARE] = "grids/game/%d?dimensions=512x512,1024x1024"
			"&mimes=image/png,image/jpeg&types=static",
		[TM_ART_ICON] = "icons/game/%d?mimes=image/png&types=static",
		[TM_ART_HERO] = "heroes/game/%d?mimes=image/png,image/jpeg"
			"&types=static",
	};
	if (tm_key() == NULL) {
		GPtrArray *none = g_ptr_array_new();
		fn(kind, none, "Add your SteamGridDB API key in Settings first.",
			data);
		g_ptr_array_unref(none);
		return;
	}
	struct art_call *c = g_new0(struct art_call, 1);
	c->kind = kind;
	c->fn = fn;
	c->data = data;
	char *path = g_strdup_printf(paths[kind], game);
	char *url = g_strconcat(API "/", path, NULL);
	char *a = auth();
	tm_http_get(url, a, art_got, c);
	g_free(a);
	g_free(url);
	g_free(path);
}
