using System.Text;
using System.Text.RegularExpressions;
using Engine.Graphics.Shader;

namespace Engine.Resource.Loader;

public partial class ProgramLoader : IResourceLoader
{
  [GeneratedRegex(@"^//\s+#type\s+(?<type>[a-z]+)$", RegexOptions.Compiled)]
  private static partial Regex TypeRegex();

  public object Load(string parPath, IResourceStreamProvider parStreamProvider)
  {
    var textReader = new StreamReader(parStreamProvider.GetStream(parPath));

    var vertexSource = new StringBuilder();
    var fragmentSource = new StringBuilder();
    var inFragment = false;
    var inVertex = false;

    while (textReader.ReadLine() is { } line)
    {
      var match = TypeRegex().Match(line);
      if (match.Success)
      {
        inVertex = match.Groups["type"].Value == "vertex";
        inFragment = match.Groups["type"].Value == "fragment";
      }
      else if (inVertex)
      {
        vertexSource.AppendLine(line);
      }
      else if (inFragment)
      {
        fragmentSource.AppendLine(line);
      }
    }

    return new Program(vertexSource.ToString(), fragmentSource.ToString());
  }
}