/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#pragma once

#include "FontAtlasGeneratorBase.hpp"
#include "SubpixelLayout.hpp"
#include "Shelf.hpp"

namespace OpenVulkano::Scene
{
	class FontPixelSizeConfig
	{
	public:
		FontPixelSizeConfig(float size = 24.f, float dpi = 72.f, bool isPixelSize = true)
		    : m_size(size), m_dpi(dpi), m_isPixelSize(isPixelSize)
		{
		}
		void SetSize(float size) { m_size = size; }
		void SetDpi(float dpi) { m_dpi = dpi; }
		void SetIsPixelSize(bool isPixelSize) { m_isPixelSize = isPixelSize; }
		[[nodiscard]] float GetSize() const { return m_size; }
		[[nodiscard]] float GetDpi() const { return m_dpi; }
		[[nodiscard]] bool GetIsPixelSize() const { return m_isPixelSize; }
		[[nodiscard]] unsigned CalculatePixelSize() const { return m_isPixelSize ? m_size : (m_size * m_dpi) / 72.0f; }
	private:
		float m_size;
		float m_dpi;
		bool m_isPixelSize;
	};

	class BitmapFontAtlasGenerator : public FontAtlasGeneratorBase
	{
	public:
		BitmapFontAtlasGenerator(FontPixelSizeConfig config = FontPixelSizeConfig(),
		                         std::optional<SubpixelLayout> subpixelLayout = std::nullopt)
		    : FontAtlasGeneratorBase(subpixelLayout.has_value() && *subpixelLayout < SubpixelLayout::UNKNOWN ? 4 : 1)
		    , m_pixelSizeConfig(config)
		    , m_subpixelLayout(subpixelLayout.value_or(SubpixelLayout::UNKNOWN))
		{
		}
		void GenerateAtlas(const std::string& fontFile, const std::set<uint32_t>& charset,
		                   const std::optional<std::string>& pngOutput = std::nullopt) override;
		void GenerateAtlas(const Array<char>& fontData, const std::set<uint32_t>& charset,
		                   const std::optional<std::string>& pngOutput = std::nullopt) override;
	private:
		void Generate(const std::variant<std::string, Array<char>>& source, const std::set<uint32_t>& chset, const std::optional<std::string>& pngOutput);
		void FillGlyphsInfo(const std::vector<GlyphForPacking>& allGlyphs, const FtFaceRecPtr& face, double scaleFactor);
		void FillSubpixelData(const FT_Bitmap& bitmap, const GlyphForPacking& glyph);
		FT_Int32 GetGlyphRenderMode() const;
		// tmp function
		Math::Vector2ui ScaleGlyphSize(unsigned int w, unsigned int h) const;
		std::pair<std::vector<GlyphForPacking>, double> InitGlyphsForPacking(const std::set<uint32_t>& chset, const FtFaceRecPtr& face);
	private:
		FontPixelSizeConfig m_pixelSizeConfig;
		SubpixelLayout m_subpixelLayout;
	};
}
