#include "cFont.hpp"

/*** Custom Header Files ***/
#include "../UtilityEngine/cUtility.hpp"

using TextTypeEngine::cFont;
using TextTypeHelpers::cFontHolder;
using UtilityEngine::cUtility;

cFont::cFont( const cString& filename /*= ""*/, const cString& dir /*= ""*/, const unsigned long int size /*= 16*/ )
: m_dir(dir), m_fileName(filename), mpp_default(nullptr)
{
	setSize(size);
}

cFont::cFont( const cFont& copy )
: m_dir(copy.getDir()), m_fileName(copy.getFileName()), mpp_default(nullptr)
{
	setSize(copy.getSize());
}

cFont::~cFont()
{
	UnloadFont();
}

///Functions
///Sets
void cFont::setDir( const cString& dir )
{
	m_dir = dir;
}

void cFont::setFileName( const cString& filename )
{
	m_fileName = filename;
}

void cFont::setFileNameandDir( const cString& filename, const cString& dir /*= ""*/ )
{
	setDir(dir);
	setFileName(filename);
}

void cFont::setSize( const unsigned long int size /*= 16*/ )
{
	while ((mpp_default == nullptr) || ((*mpp_default) == nullptr)) {
		getFont(size);
		mpp_default = (cFontHolder**)getFontHolder(size);
	}
}

///Gets
const cString& cFont::getDir() const
{
	return m_dir;
}

const cString& cFont::getFileName() const
{
	return m_fileName;
}

const unsigned long int cFont::getSize() const
{
	return (*mpp_default)->getSize();
}

TTF_Font* cFont::getFont()
{
	return (*mpp_default)->getFont();
}

TTF_Font* cFont::getFont( const unsigned long int size )
{
	TTF_Font* rtn = nullptr;
	
	rtn = getFontHolder(size)->getFont();
	//We Can't find the Font in that size so we make a new one
	if (rtn == nullptr) {
		rtn = LoadFont(size);
	}

	return rtn;
}

//private:
TTF_Font* cFont::LoadFont( const unsigned long int size )
{
	TTF_Font* rtn = nullptr;
	if (m_fileName != "") {
		cString temp = m_dir + m_fileName;
		if ((rtn = TTF_OpenFont(temp.c_str(), size)) == nullptr)
			cUtility::Inst().Message("Unable to load necessary TTF file. " + temp + " TTF_OpenFont():", "", cUtility::eTypeSDL::TTF);
		else {
			cFontHolder* holder = new cFontHolder(rtn, size);
			m_fonts.push_back(holder);
		}
	}
	return rtn;
}

TextTypeHelpers::cFontHolder* cFont::getFontHolder(const unsigned long int size)
{
	cFontHolder* rtn = nullptr;
	std::vector<cFontHolder*>::iterator it;

	for (it = m_fonts.begin(); it < m_fonts.end(); it++) {
		if (size == (*it)->getSize()) {
			rtn = (*it);
			//break out of the for loop
			break;
		}
	}
	return rtn;
}

void cFont::UnloadFont()
{
	m_fonts.clear();
}