using System.Runtime.InteropServices;
using Engine.Graphics.Pixel;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

namespace Engine.Resource.Loader;

public class ImageLoader : IResourceLoader
{
  public object Load(string parPath, IResourceStreamProvider parStreamProvider)
  {
    using var stream = parStreamProvider.GetStream(parPath);
    return Load(stream);
  }

  internal static Asset.Image<Rgba8> Load(Stream parStream)
  {
    var sharpImage = SixLabors.ImageSharp.Image.Load<Rgba32>(parStream);
    if (sharpImage == null)
    {
      throw new InvalidOperationException($"Failed to load image from stream");
    }

    sharpImage.Mutate(parImageContext => parImageContext.Flip(FlipMode.Vertical));

    var image = new Asset.Image<Rgba8>(sharpImage.Width, sharpImage.Height);
    var span = MemoryMarshal.CreateSpan(ref MemoryMarshal.GetArrayDataReference(image.Pixels),
      image.Pixels.Length * Marshal.SizeOf<Rgba8>());
    sharpImage.CopyPixelDataTo(span);

    return image;
  }
}