/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "game/renderer/font.hpp"

#include "common/logger.hpp"

#include <locale>
#include <codecvt>

using namespace polygun::renderer;

static unsigned g_ft_refs = 0;
static FT_Library g_ft;

Font::Font() :
	m_face(nullptr),
	m_prev_size(0)
{
	if(g_ft_refs==0 && FT_Init_FreeType(&g_ft))
		LOG_FATAL("Failed to initialize FreeType 2");
	g_ft_refs++;
}

Font::~Font() {
	if(m_face)
		FT_Done_Face(m_face);
	g_ft_refs--;
	if(g_ft_refs==0)
		FT_Done_FreeType(g_ft);
}

bool Font::load_from_file(const std::string& path) {
	if(FT_New_Face(g_ft, path.c_str(), 0, &m_face))
		return false;
	return true;
}

void Font::render_glyphs(const std::string& text, unsigned size, const glm::vec4ub& color, std::vector<std::unique_ptr<RasterizedGlyph>>& output) {
	if(text.empty())
		return;
	if(size!=m_prev_size) {
		if(FT_Set_Char_Size(m_face, 0, size*64, 0, 0)) {
			LOG_ERROR("Failed to set size %d for Font %p", size, this);
			return;
		}
		m_prev_size = size;
	}

	// FIXME: Replace deprecated std::codecvt_utf8
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
	std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
	std::u32string converted = converter.from_bytes(text);
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
	unsigned text_line_y = 0;
	for(char32_t ch : converted) {
		output.push_back(render_glyph(ch, size, color));
		RasterizedGlyph* glyph = output.back().get();
		if(glyph->m_height>text_line_y)
			text_line_y = glyph->m_height;
	}

	unsigned x_pos = 0;
	for(std::unique_ptr<RasterizedGlyph>& glyph : output) {
		glyph->m_x = x_pos;
		glyph->m_y = text_line_y-glyph->m_top;
		x_pos+=glyph->m_width;
	}
}

void Font::render_glyphs_in_area(const glm::vec2& area_size, const std::string& text, unsigned size, const glm::vec4ub& color, std::vector<std::unique_ptr<RasterizedGlyph>>& output) {
	if(text.empty())
		return;
	if(size!=m_prev_size) {
		if(FT_Set_Char_Size(m_face, 0, size*64, 0, 0)) {
			LOG_ERROR("Failed to set size %d for Font %p", size, this);
			return;
		}
		m_prev_size = size;
	}

	// FIXME: Replace deprecated std::codecvt_utf8
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
	std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
	std::u32string converted = converter.from_bytes(text);
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
	unsigned x_pos = 0;
	unsigned y_pos = 0;
	unsigned text_line_y = 0;
	unsigned glyph_in_line_count = 0;
	std::vector<GlyphPositionInfo> glyph_positions;

	for(char32_t ch : converted) {
		output.push_back(render_glyph(ch, size, color));
		RasterizedGlyph* glyph = output.back().get();
		x_pos+=glyph->m_width;
		if(y_pos>area_size.y)
			break;
		if(x_pos+glyph->m_width<area_size.x) {
			if(glyph->m_height>text_line_y)
				text_line_y = glyph->m_height;
		}
		else {
			x_pos = 0;
			glyph_positions.push_back(GlyphPositionInfo{text_line_y, glyph_in_line_count});
			glyph_in_line_count = 0;
			y_pos+=text_line_y;
			text_line_y = 0;
		}
		glyph_in_line_count++;
	}
	if(glyph_in_line_count>0)
		glyph_positions.push_back(GlyphPositionInfo{text_line_y, glyph_in_line_count});

	size_t glyph_counter = 0;
	unsigned glyph_line = 0;
	x_pos = 0;
	y_pos = 0;
	for(std::unique_ptr<RasterizedGlyph>& glyph : output) {
		const GlyphPositionInfo& position_info = glyph_positions[glyph_line];
		glyph->m_x = x_pos;
		glyph->m_y = y_pos+position_info.m_text_line_y-glyph->m_top;
		x_pos+=glyph->m_width;

		glyph_counter++;
		if(glyph_counter==position_info.m_glyph_count) {
			glyph_counter = 0;
			x_pos = 0;
			y_pos+=position_info.m_text_line_y+12;
			glyph_line++;
		}
	}
}

std::unique_ptr<Surface> Font::render_text(const std::vector<std::unique_ptr<RasterizedGlyph>>& glyphs) {
	std::unique_ptr<Surface> result;
	unsigned final_surface_width = 0;
	unsigned final_surface_height = 0;
	for(const std::unique_ptr<RasterizedGlyph>& glyph : glyphs) {
		const unsigned right_point = glyph->m_x+glyph->m_width;
		const unsigned bottom_point = glyph->m_y+glyph->m_height;
		if(right_point>final_surface_width)
			final_surface_width = right_point;
		if(bottom_point>final_surface_height)
			final_surface_height = bottom_point;
	}

	result = std::make_unique<Surface>(final_surface_width, final_surface_height, glm::vec4ub(0, 0, 0, 0));
	for(const std::unique_ptr<RasterizedGlyph>& glyph : glyphs)
		result->blit_surface(glyph->m_x, glyph->m_y, *glyph->m_surface);

	return result;
}

std::unique_ptr<Surface> Font::render_text(const std::string& text, unsigned size, const glm::vec4ub& color) {
	std::vector<std::unique_ptr<RasterizedGlyph>> character_surfaces;
	render_glyphs(text, size, color, character_surfaces);

	return render_text(character_surfaces);
}

std::unique_ptr<Surface> Font::render_text_in_area(const glm::vec2& area_size, const std::string& text, unsigned size, const glm::vec4ub& color) {
	std::vector<std::unique_ptr<RasterizedGlyph>> character_surfaces;
	render_glyphs_in_area(area_size, text, size, color, character_surfaces);

	return render_text(character_surfaces);
}

std::unique_ptr<Font::RasterizedGlyph> Font::render_glyph(unsigned charcode, unsigned size, const glm::vec4ub& color) {
	std::unique_ptr<RasterizedGlyph> result = std::make_unique<Font::RasterizedGlyph>();

	unsigned char_index = FT_Get_Char_Index(m_face, charcode);
	if(FT_Load_Glyph(m_face, char_index, FT_LOAD_DEFAULT)) {
		LOG_ERROR("Failed to load glyph image for codepoint %d", charcode);
		return result;
	}
	if(m_face->glyph->format!=FT_GLYPH_FORMAT_BITMAP && FT_Render_Glyph(m_face->glyph, FT_RENDER_MODE_NORMAL)) {
		LOG_ERROR("Failed to render glyph image for codepoint %d", charcode);
		return result;
	}

	FT_Bitmap bitmap = m_face->glyph->bitmap;
	const size_t pixels_size = bitmap.width*bitmap.rows*4;
	uint8_t* pixels = new uint8_t[pixels_size];
	memset(pixels, 0, pixels_size);

	if(!isspace(charcode)) {
		switch(bitmap.pixel_mode) {
		case FT_PIXEL_MODE_NONE:
			LOG_ERROR("Invalid glyph pixel mode");
			return result;
		case FT_PIXEL_MODE_MONO:
			convert_ft_mono_pixels(bitmap, color, pixels);
			break;
		case FT_PIXEL_MODE_GRAY:
			convert_ft_gray_pixels(bitmap, color, pixels);
			break;
		default:
			LOG_ERROR("(FIXME) Unsupported glyph pixel mode: %d", bitmap.pixel_mode);
			return result;
		}
	}

	result->m_surface = std::make_unique<Surface>(bitmap.width, bitmap.rows, pixels);
	delete[] pixels;
	result->m_width = m_face->glyph->advance.x>>6;
	result->m_height = m_face->glyph->metrics.height>>6;
	result->m_top = m_face->glyph->bitmap_top;
	return result;
}

void Font::convert_ft_mono_pixels(const FT_Bitmap& bitmap, const glm::vec4ub& color, uint8_t* pixels) {
	for(unsigned y = 0; y<bitmap.rows; y++) {
		for(unsigned x = 0; x<bitmap.width; x++) {
			const unsigned index = y*std::abs(bitmap.pitch)+(x>>3); // shifting x 3 times to the right is actually dividing by 8
			const uint8_t offset = x&7; // offset = x%8
			const uint8_t pixel = (bitmap.buffer[index]>>(7-offset))&1;
			if(pixel) {
				pixels[(y*bitmap.width+x)*4] = color.r;
				pixels[(y*bitmap.width+x)*4+1] = color.g;
				pixels[(y*bitmap.width+x)*4+2] = color.b;
				pixels[(y*bitmap.width+x)*4+3] = 255;
			}
		}
	}
}

void Font::convert_ft_gray_pixels(const FT_Bitmap& bitmap, const glm::vec4ub& color, uint8_t* pixels) {
	for(unsigned y = 0; y<bitmap.rows; y++) {
		for(unsigned x = 0; x<bitmap.width; x++) {
			uint8_t alpha;
			if(bitmap.num_grays==256)
				alpha = bitmap.buffer[y*std::abs(bitmap.pitch)+x];
			else {
				const uint8_t px = bitmap.buffer[y*std::abs(bitmap.pitch)+x];
				alpha = static_cast<float>(px)/(bitmap.num_grays-1)*255;
			}
			if(alpha>0) {
				pixels[(y*bitmap.width+x)*4] = color.r;
				pixels[(y*bitmap.width+x)*4+1] = color.g;
				pixels[(y*bitmap.width+x)*4+2] = color.b;
				pixels[(y*bitmap.width+x)*4+3] = alpha;
			}
		}
	}
}
