using System.Numerics;
using Voile.Input;
using Voile.Rendering;
using Voile.Resources;

namespace Voile.UI.Widgets;

public class Label : Widget
{
    public override Rect MinimumSize => _textSize;

    public string Text
    {
        get => _text; set
        {
            _text = value;
            MarkDirty();
        }
    }

    public override string? StyleElementName => nameof(Label);

    /// <summary>
    /// <see cref="FontSet"/> to use with this label.
    /// </summary>
    public FontSet FontSet { get; set; } = new();

    public Label(string text, ResourceRef<Font> fontOverride)
    {
        _text = text;

        FontSet.AddFont(fontOverride);

        MarkDirty();
        Update();
    }

    public Label(string text, FontSet fontSet)
    {
        _text = text;

        FontSet = fontSet;

        MarkDirty();
        Update();
    }

    protected override void OnInput(UIInputContext action)
    {

    }

    protected override void OnRender(RenderSystem renderer, Style style)
    {
        renderer.SetTransform(GlobalPosition, Vector2.Zero);
        renderer.DrawText(_suitableFont, _text, style.TextColor ?? Color.Black);
    }

    protected override void OnUpdate()
    {
        ResourceRef<Font> fontRef = ResourceRef<Font>.Empty();
        foreach (var c in _text)
        {
            if (FontSet.TryGetFontFor(c, out var fallbackFont))
            {
                if (fallbackFont != fontRef)
                {
                    fontRef = fallbackFont;
                }
            }
        }

        _suitableFont = fontRef;

        var font = _suitableFont.Value;
        _textSize = font.Measure(_text);

        Size = _textSize;
    }

    private ResourceRef<Font> _suitableFont = ResourceRef<Font>.Empty();

    private string _text = "Hello, World!";
    private Rect _textSize = Rect.Zero;
}