
using Godot;


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

    [ExportToolButton( "Set Reference Name" )]
    public Callable setReferencedNameButton => Callable.From(
      ()=>
      { 
        if ( referencedSequenceAction == null )
        {
          this.Name = "* (nothing)";
        }
        else
        {
          this.Name = "* " + referencedSequenceAction.Name;
        }
      }
    );

    protected override void _OnTrigger()
    {
      if ( ! IsInstanceValid( referencedSequenceAction ) )
      { 
        return;
      }

      var ownID = DispatchStart();
      var referenceID = -1;      

      System.Action<SequenceActionFinishedEvent> callback = ( se )=>
        {
          if ( se.id != referenceID )
          {
            return;
          }

          if ( se.success )
          { 
            DispatchEnd( ownID ); 
          }
          else 
          {
            DispatchCancelled( ownID );
          }
        }
      ;

      referencedSequenceAction.onSequenceDone.Once( callback );  

      referenceID = referencedSequenceAction.TriggerSequenceAndGetID();

      if ( referenceID == -1 )
      {
        referencedSequenceAction.onSequenceDone.RemoveAction( callback );
        DispatchCancelled( ownID );
      }
    }
  }

}