#include "font.h"

#include "image.h"
#include "tileset.h"

font::font(resource_manager& rm, ini_category const* ini, std::string const& path, std::vector<uint8_t> const& data) {
	if(!ini)
		throw std::runtime_error("font needs assets.ini");
	if(ini->get<bool>("proportional")) {
		auto image = rm.get<::image>(path);
		auto x = 0;
		std::vector<int> slices;
		for(int i = 0; i < image->size().x; ++i) {
			if(image->get(vec2i(i, 0)) & 0xff000000)
				slices.push_back(i);
		}
		int count = slices.size();
		slices.push_back(image->size().x);
		_lineheight = image->size().y - 1;

		auto charset = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'abcdefghijklmnopqrstuvwxyz{|}~";
		for(int i = 0; i < count; ++i) {
			auto r = recti(vec2i(slices[i], 1), vec2i(slices[i + 1] - slices[i], _lineheight));
			//auto img = ::image(r.size);
			auto ch = charset[i];
			_glyphs.emplace(ch, r.size);
			_glyphs.at(ch).clear(0);
			_glyphs.at(ch).draw(image, vec2i::zero, r);
		}
	} else {
		int width = ini->get<int>("width");
		int height = ini->get<int>("height");
		auto ts = rm.get<tileset>(path);
		_lineheight = ts->_tile_size.y;
		for(int i = 0; i < 256; ++i) {
			_glyphs.insert({ i, ts->_tiles[i] });
		}
	}
}

image const* font::get(char ch) const {
	if(_glyphs.contains(ch))
		return &_glyphs.at(ch);
	else
		return &_glyphs.at(' ');
}

int font::lineheight() const {
	return _lineheight;
}
