<?php

namespace PHPNative\Framework;

/**
 * Central registry for icon fonts (e.g. Font Awesome) used by UI components.
 * Provides lazy loading and caching of TTF font handles per font path/size.
 */
class IconFontRegistry
{
    private static null|string $defaultFontPath = null;

    /** @var array<string,array<int,resource>> */
    private static array $loadedFonts = [];

    /**
     * Define the default font that should be used for icons.
     * Calling this clears any previously cached fonts for other paths.
     */
    public static function setDefaultFontPath(string $fontPath): void
    {
        if (!is_file($fontPath)) {
            throw new \InvalidArgumentException("Icon font not found at path: {$fontPath}");
        }

        if (self::$defaultFontPath !== $fontPath) {
            self::clear();
            self::$defaultFontPath = $fontPath;
        }
    }

    public static function getDefaultFontPath(): null|string
    {
        return self::$defaultFontPath;
    }

    /**
     * Resolve (and lazily load) a font handle for the requested size.
     *
     * @return resource|null
     */
    public static function getFont(int $size, null|string $fontPath = null)
    {
        $path = $fontPath ?? self::$defaultFontPath;
        if ($path === null) {
            return null;
        }

        $key = $path . '|' . $size;

        if (isset(self::$loadedFonts[$key]) && is_resource(self::$loadedFonts[$key])) {
            return self::$loadedFonts[$key];
        }

        $font = @ttf_open_font($path, $size);
        if ($font === false) {
            return null;
        }

        self::$loadedFonts[$key] = $font;

        return $font;
    }

    /**
     * Close all cached font handles.
     */
    public static function clear(): void
    {
        foreach (self::$loadedFonts as $font) {
            if (is_resource($font)) {
                @ttf_close_font($font);
            }
        }
        self::$loadedFonts = [];
    }
}
