package jnpf.culture.util;

import java.awt.*;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 字体缓存工具类
 *
 * @author yanwenfu
 * @create 2025-12-31
 */
public class FontUtil {

    // 缓存字体： key = 路径 + size
    private static final Map<String, Font> FONT_CACHE = new ConcurrentHashMap<>();

    /**
     * 加载字体并缓存
     * @param path 字体文件路径，相对于 classpath，例如 "/fonts/MiSans-Semibold.ttf"
     * @param size 字体大小（pt）
     * @return Font 对象
     */
    public static Font loadFont(String path, float size) {
        String cacheKey = path + "_" + size;
        if (FONT_CACHE.containsKey(cacheKey)) {
            return FONT_CACHE.get(cacheKey);
        }

        try (InputStream is = FontUtil.class.getResourceAsStream(path)) {
            if (is == null) {
                throw new RuntimeException("字体文件未找到: " + path);
            }
            Font baseFont = Font.createFont(Font.TRUETYPE_FONT, is);
            Font font = baseFont.deriveFont(Font.PLAIN, size);
            FONT_CACHE.put(cacheKey, font);
            return font;
        } catch (Exception e) {
            throw new RuntimeException("加载字体失败: " + path, e);
        }
    }

    /**
     * 清空字体缓存（可选）
     */
    public static void clearCache() {
        FONT_CACHE.clear();
    }
}
