using System.Text.Json;
using Engine.Asset.Font;
using Engine.Asset.Font.Metadata;

namespace Engine.Resource.Loader;

public class FontLoader : IResourceLoader
{
  public object Load(string parPath, IResourceStreamProvider parStreamProvider)
  {
    var metadataPath = Path.Combine(parPath, "metadata.json");
    using var metadataStream = parStreamProvider.GetStream(metadataPath);
    var metadata = JsonSerializer.Deserialize<Metadata>(metadataStream);

    if (metadata == null)
    {
      throw new InvalidOperationException($"Failed to load metadata from {metadataPath}");
    }

    var atlasPath = Path.Combine(parPath, "atlas.png");
    using var atlasStream = parStreamProvider.GetStream(atlasPath);
    var atlasImage = ImageLoader.Load(atlasStream);

    // TODO: We should not be using engine instance here
    var atlasTexture = Engine.Instance.Renderer.Schedule(() => atlasImage.ToStaticTexture()).Result;

    return new Font(atlasTexture, metadata);
  }
}