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

namespace Rokojori
{ 
  [Tool]
  [GlobalClass]
  public partial class TextureMask:SpatialMask
  {     
    [Export]
    public string name = "TextureMask";   

    [Export]
    public string UV = "UV";
    
    [Export]
    public ColorChannelType colorChannel = ColorChannelType.Red;

    [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> GetMaskCode( ShaderGenerationContext context, string contextName, string maskName )
    {
      var prefix = contextName + name;
      var uniformGroup = contextName + "TextureMask";

      if ( ShaderPhase.Includes == context.phase )
      {
        var list = IncludeLightLibrary();

        if ( ColorChannelTypeUtility.NeedsIncludesForGLSLMember( colorChannel ) )
        {
          list.AddRange( IncludeColorsLibrary() );
        }

        return list;
      }
      else if ( ShaderPhase.Variables == context.phase )
      {
        var hints = TextureModule.GetTextureHints( srgb, false, repeat, filter, textureDefault ); 
        var fresnelVariablesCode =

        $@"
        uniform sampler2D {prefix}TextureMask:{hints.Join()}; 

        ";

        return AsUniformGroup( uniformGroup, ToCode( fresnelVariablesCode.Indent( "" ) ) );
      }
      else if ( context.isFragmentPhase )
      {
        var member = ColorChannelTypeUtility.ToGLSLMember( "textureValue", colorChannel );
        var code = 
        @$"
        
        {{
        
        vec4 textureValue = texture( {prefix}TextureMask, {UV} );
        {maskName} = {member};  
        }}

        ;";
        return ToCode( code.Indent( "    " ) );
      }

      return null;
    }
   
  }
}