using Godot;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;

namespace Rokojori
{ 
  [Tool]
  [GlobalClass]
  public partial class FadingModule:ShaderGenerationModule
  {     
    [Export]
    public AlphaFadeMode alphaFadeMode = AlphaFadeMode.NoiseDitherDiscard; 

    [Export]
    public FadingModifier[] fadingModifiers = [];


    public override List<ShaderVariant> GetVariants( ShaderGenerationContext context )
    {
    
      if ( fadingModifiers == null )
      {
        return null ;
      }

      var list = fadingModifiers.ToList().FilterNulls();

      if ( list.Count == 0 )
      {
        return null;
      }

      

      var shaderCode = new List<ShaderCode>(); 

      if ( ShaderPhase.Includes == context.phase )
      {
        shaderCode.Add( IncludeNoiseLibrary() );
      }

      list.ForEach(
        ( fm )=>
        {
          var fIndex = list.Filter( l => l.IsSameType( fm ) ).IndexOf( fm );
          var fCode = fm.GetFadingCode( context, fIndex, alphaFadeMode );

          if ( fCode == null )
          {
            return;
          }

          if ( ShaderPhase.Variables == context.phase && fm.createUniformGroup )
          {
            shaderCode.Add( EndUniformGroup() );
            fm.uniformGroup = "Fading";
            fCode = fm.AsUniformGroup( fm.GetType().Name + fm.GetSuffix( fIndex ), fCode );
          }

          shaderCode.Add( fCode );

          if ( ShaderPhase.Variables == context.phase && fm.createUniformGroup )
          {
            shaderCode.Add( StartUniformGroup( "Fading") );
          }
        }
      );

      if ( ShaderPhase.Variables == context.phase )
      {
        shaderCode = AsUniformGroup( "Fading", shaderCode );
      }

      

      return ToVariants( shaderCode );
    }


  }
}