using System.Diagnostics.CodeAnalysis;

namespace Voile.Resources;

/// <summary>
/// Contains a set of multiple fonts. Used to fetch fonts based on availability of glyphs.
/// </summary>
public class FontSet
{
    public FontSet() { }

    public FontSet(IEnumerable<ResourceRef<Font>> fonts)
    {
        _fonts = fonts.ToList();
    }

    public void AddFont(ResourceRef<Font> font) => _fonts.Add(font);

    /// <summary>
    /// Tries to get a suitable font that has a given character.
    /// </summary>
    /// <param name="c">Character to get a suitable font for.</param>
    /// <param name="result">Font that contains this character.</param>
    /// <returns><c>true</c> if a font that contains this character exists, <c>false</c> otherwise.</returns>
    public bool TryGetFontFor(char c, [NotNullWhen(true)] out ResourceRef<Font>? result)
    {
        result = ResourceRef<Font>.Empty();
        foreach (var fontRef in _fonts)
        {
            if (!fontRef.TryGetValue(out var font))
            {
                return false;
            }

            if (font.HasGlyph(c))
            {
                result = fontRef;
                return true;
            }
        }
        return false;
    }

    private List<ResourceRef<Font>> _fonts = new();
}