#include "text.h"

Text::Text()
{
	mSprite = new Sprite();
	init(nullptr, nullptr, 0, 0);
}

Text::~Text()
{
	delete mSprite;
}

void Text::init(LTexture *texture, SDL_Renderer *renderer, Uint8 height)
{
	// Inicializa variables
	mHeight = height;

	// Inicia los valores del sprite que dibuja las letras
	mSprite->setWidth(mHeight);
	mSprite->setHeight(mHeight);
	mSprite->setPosX(0);
	mSprite->setPosY(0);
	mSprite->setTexture(texture);
	mSprite->setRenderer(renderer);
	mSprite->setSpriteClip(0, 0, mSprite->getWidth(), mSprite->getHeight());

	// Cadena con los caracteres ascii que se van a inicializar
	std::string text = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ{\\[]]^_`abcdefghijklmnopqrstuvwxyz";

	// Inicializa a cero el vector con las coordenadas
	for (Uint8 i = 0; i < 255; i++)
	{
		mOffset[i].x = 0;
		mOffset[i].y = 0;
		mOffset[i].w = 0;
	}

	// Establece las coordenadas para cada caracter ascii de la cadena y su ancho
	for (Uint8 i = 0; i < text.length(); ++i)
	{
		mOffset[int(text[i])].x = ((int(text[i]) - 32) % 15) * mSprite->getWidth();
		mOffset[int(text[i])].y = ((int(text[i]) - 32) / 15) * mSprite->getHeight();
		mOffset[int(text[i])].w = mHeight;
		mOffset[int(text[i])].h = mHeight;
	}
}

void Text::write(int x, int y, std::string text, Sint8 kerning, Uint8 lenght)
{
	Uint16 shift = 0;
	std::string text2;
	
	if (lenght > 0)
		text2 = text.substr(0, lenght);
	else
		text2 = text;

	for (Uint8 i = 0; i < text2.length(); ++i)
	{
		mSprite->setSpriteClip(mOffset[int(text2[i])].x, mOffset[int(text2[i])].y, mSprite->getWidth(), mSprite->getHeight());
		mSprite->setPosX(x + shift);
		mSprite->setPosY(y);
		mSprite->render();
		shift += (mOffset[int(text2[i])].w + kerning);
	}
}

void Text::writeColored(int x, int y, std::string text, Uint8 R, Uint8 G, Uint8 B)
{
	mSprite->getTexture()->setColor(R, G, B);
	write(x, y, text);
	mSprite->getTexture()->setColor(255, 255, 255);
}

void Text::writeCentered(int x, int y, std::string text, int kerning)
{
	// Uint16 lenght = Text::lenght(text, kerning);
	x = x - (Text::lenght(text, kerning) / 2);
	Uint16 shift = 0;
	for (Uint8 i = 0; i < text.length(); ++i)
	{
		mSprite->setSpriteClip(mOffset[int(text[i])].x, mOffset[int(text[i])].y, mSprite->getWidth(), mSprite->getHeight());
		mSprite->setPosX(x + shift);
		mSprite->setPosY(y);
		mSprite->render();
		shift += (mOffset[int(text[i])].w + kerning);
	}
}

Uint16 Text::lenght(std::string text, int kerning)
{
	Uint16 shift = 0;
	for (Uint8 i = 0; i < text.length(); ++i)
	{
		shift += (mOffset[int(text[i])].w + kerning);
	}
	return shift;
}

Uint8 Text::getHeight()
{
	return mHeight;
}

void Text::setHeight(Uint8 size)
{
	mHeight = size;
}