
using Godot;
using System.Collections.Generic;

namespace Rokojori
{  
  public class RG_SwapRepeat:RGGraphProcessor
  {
    protected RG_TextureSlotEditable _input;
    protected RG_TextureSlotEditable _output;

    public CompositorEffectGraphTextureSlot input => _input;
    public CompositorEffectGraphTextureSlot output => _output;

    
    public CEG_ImageProcessor imageProcessor;
    public int repeats = 1;

    public System.Action onStart; 
    public System.Action<int> onPreProcess; 
    public System.Action<int> onPostProcess; 
    public System.Action onEnd; 

    public RG_SwapRepeat( RDGraph graph ):base( graph )
    {
      _input = new RG_TextureSlotEditable( this );
      _output = new RG_TextureSlotEditable( this );
    } 

    public void SetTextureSlotInputs( RDGraphTextureSlotInput inputSlot, RDGraphTextureSlotInput outputSlot )
    {
      inputSlot.ConnectTo( input );
      outputSlot.ConnectTo( output );
    }

    public void SetTextureSlotInputs( CEG_ImageProcessor imageProcessorBefore )
    {
      imageProcessorBefore.input.ConnectTo( input );
      imageProcessorBefore.output.ConnectTo( output );
    }

    public override void Process()
    {
      if ( onStart != null )
      { 
        onStart(); 
      }

      var cachedInputTexture  = input.ResolveTexture();
      var cachedOutputTexture = output.ResolveTexture();

      imageProcessor.SetTextureSlotInputs( input, output );

      for ( int i = 0; i < repeats; i++ )
      {
        graph.context.Verbose( "Repeat:", i );

        if ( i % 2 == 0 )
        {
          _input.SetTexture( cachedInputTexture );
          _output.SetTexture( cachedOutputTexture );
        }
        else
        {
          _input.SetTexture( cachedOutputTexture );
          _output.SetTexture( cachedInputTexture );
        }

        if ( onPreProcess != null )
        { 
          onPreProcess( i ); 
        }

        imageProcessor.Process();

        if ( onPostProcess != null )
        { 
          onPostProcess( i ); 
        }
      }

      _input.SetTexture( cachedInputTexture );
      _output.SetTexture( cachedOutputTexture );

      if ( onEnd != null )
      { 
        onEnd(); 
      }

      

    } 

    
  }
}