using Engine.Scene.Component.BuiltIn.Renderer;
using OpenTK.Mathematics;

namespace DoomDeathmatch.Component.UI;

public class TextAlignComponent : Engine.Scene.Component.Component
{
  public Align Alignment { get; set; } = Align.Left;

  private TextRenderer _textRenderer = null!;

  private string? _cachedText;

  public override void Awake()
  {
    _textRenderer = GameObject.GetComponent<TextRenderer>()!;
  }

  public override void Update(double parDeltaTime)
  {
    if (_textRenderer.Text == null)
      return;

    if (_cachedText == _textRenderer.Text)
      return;

    _cachedText = _textRenderer.Text;
    var font = _textRenderer.Font;
    var size = font.Measure(_textRenderer.Text);
    var offset = GetOffset(size) + new Vector2(0, _textRenderer.Font.Metadata.Metrics.Descender / 4);

    GameObject.Transform.Translation.Xy = offset;
  }

  public Vector2 GetOffset(Vector2 parSize)
  {
    return Alignment switch
    {
      Align.Left => new Vector2(0, -parSize.Y / 2),
      Align.Center => new Vector2(-parSize.X / 2, -parSize.Y / 2),
      Align.Right => new Vector2(-parSize.X, -parSize.Y / 2),
      _ => throw new ArgumentOutOfRangeException(nameof(Alignment), Alignment, null)
    };
  }

  public enum Align
  {
    Left,
    Center,
    Right
  }
}