#include <stdio.h>
#include "sdl.h"
#include "interface.h"

int TextArray(TEXT text[], size_t n, char flag) {
	for (size_t i = 0; i < n; i++) {
		if (flag == TEXT_ARRAY_FREE && text[i].texture)
			SDL_DestroyTexture(text[i].texture);

		else if (flag == TEXT_ARRAY_SCAN && text[i].init == 0) {
			fputs("Found uninitialized font\n", stderr);
			return 1;
		}
	}

	return 0;
}

void PrintText(TTF_Font *font, APP *app, TEXT *dst, const char *text) {
	SDL_Surface *temp = TTF_RenderUTF8_Solid(font, text, dst->color);
	if (!temp) {
		fprintf(stderr, "AddBanner Font: %s\n", TTF_GetError());
		return;
	}

	dst->texture = SDL_CreateTextureFromSurface(app->render, temp);
	if (!dst->texture) {
		SDL_FreeSurface(temp);
		fprintf(stderr, "AddBanner Font: %s\n", TTF_GetError());
		return;
	}

	SDL_FreeSurface(temp);

	/* Write text size in to a structure */
	if (TTF_SizeText(font, text, &dst->w, &dst->h) < 0) {
		SDL_DestroyTexture(dst->texture);
		return;
	}

	dst->init = 1;
}

void AddBanner(APP *app, TEXT text, SDL_Rect rect) {
	/* Box */
	SDL_SetRenderDrawColor(app->render, 0, 0, 0, 0);

	SDL_RenderDrawRect(app->render, &rect);

	/* Text */
	if (text.w < rect.w)
		rect.w = text.w;

	SDL_RenderCopy(app->render, text.texture, NULL, &rect);
}

void AddPseudoButton(APP *app, TEXT text, const int bttn_num) {
	int rect_x = APPROX2ORIG(app->scr_width, -0.8);
	SDL_Rect rect = {
		.x = rect_x,
		.y = APPROX2ORIG(app->scr_height,  (0.75 - (0.2 * bttn_num))),
		.w = app->scr_width - (rect_x * 2),
		.h = 45
	};

	AddBanner(app, text, rect);
}

void CloseFonts(FONTS *fonts) {
	if (fonts->font1)
		TTF_CloseFont(fonts->font1);

	if (fonts->font2)
		TTF_CloseFont(fonts->font2);

	memset(fonts, 0, sizeof(FONTS));
}

int InitFonts(FONTS *fonts, const APP app) {
	memset(fonts, 0, sizeof(FONTS));

	size_t font_size = app.scr_width * app.scr_height * 8 / 403200;
	fonts->font1 = TTF_OpenFont(FONT1, font_size);

	font_size = app.scr_width * app.scr_height * 15 / 403200;
	fonts->font2 = TTF_OpenFont(FONT1, font_size);

	if (fonts->font1 == NULL || fonts->font2 == NULL) {
		fprintf(stderr, "Can not open font: %s\n", TTF_GetError());
		CloseFonts(fonts);
		return 1;
	}

	return 0;
}
