#include "font_atlas_manager.h"

std::optional<atlas_region_t> font_atlas_manager::get_or_create_glyph(
    int32_t in_glyph_id,
    const std::shared_ptr<font_face_interface>& in_font,
    float in_font_size,
    bool is_emoji)
{
    glyph_atlas_result_t result{};
    result.reason = glyph_atlas_reason_t::atlas_full;

    // **处理表情符号**
    if (is_emoji) {
        // 尝试从现有表情图集中获取
        for (auto& atlas : emoji_atlases_) {
            result = atlas.get_or_create_emoji(in_glyph_id, in_font, in_font_size);
            if (result.reason == glyph_atlas_reason_t::success) {
                return result.region;
            }
        }

        // 如果所有现有图集都已满，创建新的表情图集
        if (result.reason == glyph_atlas_reason_t::atlas_full) {
            auto& atlas = create_new_emoji_atlas();
            result = atlas.get_or_create_emoji(in_glyph_id, in_font, in_font_size);
            if (result.reason == glyph_atlas_reason_t::success) {
                return result.region;
            }
        }
    }
    // **处理普通字形**
    else {
        // 尝试从现有字形图集中获取
        for (auto& atlas : glyph_atlases_) {
            result = atlas.get_or_create_glyph(in_glyph_id, in_font, in_font_size);
            if (result.reason == glyph_atlas_reason_t::success) {
                return result.region;
            }
        }

        // 如果所有现有图集都已满，创建新的字形图集
        if (result.reason == glyph_atlas_reason_t::atlas_full) {
            auto& atlas = create_new_glyph_atlas();
            result = atlas.get_or_create_glyph(in_glyph_id, in_font, in_font_size);
            if (result.reason == glyph_atlas_reason_t::success) {
                return result.region;
            }
        }
    }

    // 如果所有尝试都失败，返回空
    return std::nullopt;
}

bitmap_glyph_atlas& font_atlas_manager::create_new_glyph_atlas(const Eigen::Vector2i& atlas_size) {
    auto& atlas = glyph_atlases_.emplace_back();
    atlas.initialize(atlas_size);
    return atlas;
}

color_emoji_atlas& font_atlas_manager::create_new_emoji_atlas(const Eigen::Vector2i& atlas_size) {
    auto& atlas = emoji_atlases_.emplace_back();
    atlas.initialize(atlas_size);
    return atlas;
}
