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

namespace Rokojori
{ 
  public class AudioGraph:AudioProcessor
  { 
    public AudioGraph( float sampleRate = 44100, int bufferSize = 1024 ):base( null )
    {
      this.sampleRate = sampleRate;
      this.SetBufferSize( bufferSize );
    }

    protected int _bufferSize = 1024;
    public override int bufferSize => audioGraph == null ? _bufferSize : audioGraph.bufferSize;

    protected int _frameIndex = -1;
    public int frameIndex => _frameIndex;

    public float sampleRate;
    public float bpm;
  

    public AudioProcessor output;

    public override bool processed 
    {
      get 
      {
        if ( audioGraph == null )
        {
          return false;
        }

        return base.processed;
      }
    }

    public override void SetProcessed()
    {
      if ( audioGraph == null )
      {
        _frameIndex ++;
        return;
      } 

      base.SetProcessed();
      
    }

    protected override void _ProcessAudio()
    {
      _nodes.ForEach( n => n.Clear() );
      output.Process();      
    } 

    List<AudioNode> _nodes = new List<AudioNode>();

    public void _Add( AudioNode node )
    {
      _nodes.Add( node );
    }

    public void Destroy( AudioNode node )
    {
      _nodes.Remove( node );
      node.Destroy();
    }

    public void SetBufferSize( int bufferSize )
    {
      _bufferSize = bufferSize;
      _zeroBuffer = new float[ bufferSize ];

      for ( int i = 0; i < bufferSize; i++ )
      {
        _zeroBuffer[ i ] = 0;
      }

      _nodes.ForEach( n => n.UpdateBuffserSize() );
    }

    float[] _zeroBuffer = new float[ 0 ];

    public float[] ClearBuffer( float[] buffer )
    {
      System.Array.Copy( _zeroBuffer, 0, buffer, 0, bufferSize );

      return buffer;
    }

  }

}