
using Godot;
using System.Collections.Generic;

namespace Rokojori
{  
  [Tool][GlobalClass, Icon("res://addons/rokojori_action_library/Icons/Parallel.svg") ]
  public partial class RepeatSequence : SequenceAction
  {
    [Export]
    public Action action;

    [Export]
    public int maxNumRepeats = 3;
    
    [Export]
    public float maxRepeatDuration = 60;

    [Export]
    public TimeLine timeLine;


    bool stopSignal = false;


    public void Stop()
    {
      stopSignal = true;
    }

    protected override void _OnTrigger()
    {
      var id = DispatchStart();

      if ( ! ( action is SequenceAction ) )
      {        
        Trigger( action );
        DispatchEnd( id );
        return;
      }

      var sa = (SequenceAction) action;

      var executed = 0;

      System.Action<SequenceActionFinishedEvent> callBack = null;

      var tl = TimeLineManager.Ensure( timeLine );

      if ( maxNumRepeats <= 0 && ( tl == null || maxRepeatDuration <= 0 ) )
      {
        return;
      }

      var startTime = tl.position;
      var endTime = tl.position + maxRepeatDuration;
      
      callBack = ( a )=>
      {
        if ( ! a.success )
        {
          DispatchCancelled( id );
          sa.onSequenceDone.RemoveAction( callBack );
          return;
        }

        executed ++;

        var finished = ( maxNumRepeats > 0 && executed >= maxNumRepeats ) || 
                       ( tl != null && tl.position >= endTime );

        finished = stopSignal || finished;

        if ( finished )
        {
          DispatchEnd( id );
          sa.onSequenceDone.RemoveAction( callBack );
          return;
        }
        else
        {
          Trigger( action );
        }
        
      };
    

      sa.onSequenceDone.AddAction( callBack );
      

      Trigger( action );

    }
  }
}