#include "font.h"
#include "SDL_ttf.h"
#include "font_manager.h"
#include "resource_locator.h"

using namespace Halley;

static int refcount = 0;

Font::Font(String _face, float _size, bool _bold, bool _italics)
	: face(_face)
	, size(_size)
	, bold(_bold)
	, italics(_italics)
	, font(nullptr)
{
	if (!TTF_WasInit()) {
		TTF_Init();
	}
	refcount++;
	
	// Load font
	auto f = FontManager::get(face);
	font = TTF_OpenFontRW(f->data->getRWOps(), 1, (int) size);
	TTF_SetFontHinting(font, TTF_HINTING_LIGHT);
	ascent = TTF_FontAscent(font);
	lineSkip = TTF_FontLineSkip(font);
}

Font::~Font()
{
	if (refcount <= 0) {
		std::cout << "Attempting to destroy a font with TTF library already deinitialized!" << std::endl;
	}

	TTF_CloseFont(font);
	font = nullptr;
	refcount--;
	if (refcount == 0) {
		TTF_Quit();
	}
}

void Font::getMetrics(int character, int& minx, int& maxx, int& miny, int& maxy, int& advance)
{
	TTF_GlyphMetrics(font, character, &minx, &maxx, &miny, &maxy, &advance);
}

SDL_Surface* Font::renderGlyph(int character)
{
	SDL_Color c0 = {255, 255, 255};
	SDL_Color c1 = {0, 0, 0};
	return TTF_RenderGlyph_Shaded(font, character, c0, c1);
}

FontFile::FontFile(String name)
{
	data = ResourceLocator::get(name);
}

FontFile::~FontFile()
{
}
