/*
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.
*/

#ifndef POLYGUN_RENDERER_FONT_HPP
#define POLYGUN_RENDERER_FONT_HPP

#include <string>
#include <memory>
#include <vector>
#include <ft2build.h>
#include FT_FREETYPE_H

#include "common/glm_ext.hpp"
#include "game/renderer/surface.hpp"

namespace polygun::renderer {
	class Surface;
	class Font final {
	public:
		struct RasterizedGlyph {
			std::unique_ptr<Surface> m_surface;
			unsigned m_x;
			unsigned m_y;
			unsigned m_width;
			unsigned m_height;
			unsigned m_top;
		};

	private:
		struct GlyphPositionInfo {
			unsigned m_text_line_y;
			size_t m_glyph_count;
		};

	public:
		Font();
		~Font();

		bool load_from_file(const std::string& path);
		void render_glyphs(const std::string& text, unsigned size, const glm::vec4ub& color, std::vector<std::unique_ptr<RasterizedGlyph>>& output);
		void 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);
		std::unique_ptr<Surface> render_text(const std::vector<std::unique_ptr<RasterizedGlyph>>& glyphs);
		std::unique_ptr<Surface> render_text(const std::string& text, unsigned size, const glm::vec4ub& color);
		std::unique_ptr<Surface> render_text_in_area(const glm::vec2& area_size, const std::string& text, unsigned size, const glm::vec4ub& color);

	private:
		FT_Face m_face;
		unsigned m_prev_size;

	private:
		std::unique_ptr<RasterizedGlyph> render_glyph(unsigned charcode, unsigned size, const glm::vec4ub& color);
		void convert_ft_mono_pixels(const FT_Bitmap& bitmap, const glm::vec4ub& color, uint8_t* pixels);
		void convert_ft_gray_pixels(const FT_Bitmap& bitmap, const glm::vec4ub& color, uint8_t* pixels);
	};
}

#endif // POLYGUN_RENDERER_FONT_HPP
