#include "color_emoji_atlas.h"

#include "interface/image_interface.h"

glyph_atlas_result_t color_emoji_atlas::get_or_create_emoji(int32_t in_glyph_index,
                                                            const std::shared_ptr<font_face_interface>& in_font, float in_font_size) {

	glyph_atlas_result_t result{};

	// 创建缓存键
	const auto& cache_key = create_cache_key(in_glyph_index, in_font->get_font_name(), in_font_size);

	// 检查缓存
	auto cached_result = find_in_cache(cache_key);
	if (cached_result.reason == glyph_atlas_reason_t::success) {
		return cached_result;
	}

	in_font->set_font_size(in_font_size);

	// 获取彩色表情位图
	auto bitmap = in_font->get_emoji_image(in_glyph_index);
	if (!bitmap) {
		result.reason = glyph_atlas_reason_t::glyph_not_found;
		return result;
	}

	// 从图集分配空间，添加2像素的padding防止纹理采样时的边缘混合问题
	const auto& region = atlas_->allocate_region(bitmap->get_size(), { 2, 2 });
	if (!region) {
		result.reason = glyph_atlas_reason_t::atlas_full;
		return result;
	}

	// 更新图集，将位图数据上传到纹理
	atlas_->update_region(bitmap->data, bitmap->get_data_size(), region->rect);

	// 缓存结果以便未来复用
	add_to_cache(cache_key, *region);

	result.reason = glyph_atlas_reason_t::success;
	result.region = *region;
	return result;
}
