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

namespace Rokojori
{ 
  [Tool]
  [GlobalClass]
  public partial class DissolveFading:FadingModifier
  {    
    [Export]
    public string UV = "UV";

    [Export]
    public bool srgb = true;

    [Export]
    public bool repeat = true;
    
    [Export]
    public TextureModule.TextureFilter filter;
    
    [Export]
    public TextureModule.TextureDefault textureDefault = TextureModule.TextureDefault.White;


    public override List<ShaderCode> GetFadingCode( ShaderGenerationContext context, int offsetIndex, AlphaFadeMode parentFadeMode )
    {
      var alphaFadeMode = GetFadeMode( parentFadeMode );
      var suffix = GetSuffix( offsetIndex );

      if ( context.isIncludesPhase )
      {
        return IncludeMathLibrary();
      }

      if ( context.isVariablesPhase )
      {
        var hints = TextureModule.GetTextureHints( srgb, false, repeat, filter, textureDefault );

        var code = 
        $@"
        uniform float dissolveState{suffix}:hint_range(0,1) = 1.0f;
        uniform sampler2D dissolveTexture{suffix}:{hints.Join()};
        ";
        return ToCode( code.Indent( "  " ) );
      }


      if ( context.isFragmentPhase )
      {
        var code = 
        $@"

       
        float sampledDissolveTexture{suffix} = texture( dissolveTexture{suffix}, {UV} ).r;
        float dissolveAlpha{suffix} = clamp01( sampledDissolveTexture + ( dissolveState{suffix} * 2.0 - 1.0 ) );  
       
        ";


        return ToCode( code.Indent( "  " ) ).Concat(  ToCode( AlphaFade.Fragment( "dissolveAlpha" + suffix, alphaFadeMode ) ) );
      }

      return [];
    }   


  }
}