// Texty.cpp

#include "Texty.h"
#include "Game.h"
#include <iostream>
#include <sstream>


GE161::Texty::Texty(std::string fontName, int fontSize, bool visible):
fontName(fontName),
visible(visible),
error(false)
{
	if (!TTF_WasInit())
	{
		int s = TTF_Init();
		if (s == -1)
		{
			fatalSDLError("In Texty constructor, TTF_Init: ", TTF_GetError());
			error = true;
			return;
		}
	}

	// Open the font
	font = TTF_OpenFont(fontName.c_str(), fontSize);
	if (font == nullptr)
	{
		fatalSDLError("In Texty constructor, TTF_OpenFont: ", TTF_GetError());
		error = true;
		return;
	}
	color = {0, 0, 0, 255 };  // any color as long as it's black, for now

	nextX = nextY = 10;
	lineStartX = nextX;
}

GE161::Texty::~Texty()
{
	if (error)
		return;
	TTF_CloseFont(font);
}

void GE161::Texty::write(std::string text, writeOption_t option)
{
	if (error)
		return;
	if (text.length() == 0)
	{
		if (option== NEXT_LINE)
		{
			nextX = lineStartX;
			nextY += TTF_FontHeight(font) + 1;
		}
		// nop if CONTINUE
		return;
	}
	//We need to first render to a surface as that's what TTF_RenderText
	//returns, then load that surface into a texture
	SDL_Surface *surface = TTF_RenderText_Blended(font, text.c_str(), color);
	if (surface == nullptr)
	{
		fatalSDLError("In Texty::write, TTF_RenderText_Blended: ", TTF_GetError());
		return;
	}

	SDL_Renderer* renderer = GE161::Game::theGame->getRenderer();

	texture = SDL_CreateTextureFromSurface(renderer, surface);
	if (texture == nullptr)	
	{
		fatalSDLError("In Texty::write, SDL_CreateTextureFromSurface: ", SDL_GetError());
		return;
	}

	int w, h;
	SDL_QueryTexture(texture, NULL, NULL, &w, &h);
	SDL_Rect dest;
	if (option == CONTINUE)
	{
		dest.x = nextX;
		dest.y = nextY;
	}
	else // option == NEXT_LINE
	{
		dest.x = lineStartX;
		dest.y = nextY + h;
	}
	dest.w = w;
	dest.h = h;
	SDL_RenderCopy(renderer, texture, NULL, &dest);
	nextX += w;
	nextY = dest.y;

	// Clean up the surface and texture
	SDL_FreeSurface(surface);
	SDL_DestroyTexture(texture);

}

void GE161::Texty::write(std::string text, int x, int y)
{
	nextX = x;
	nextY = y;
	lineStartX = x;

	write(text, CONTINUE);
}

