
using Godot;
using System.Threading.Tasks;

namespace Rokojori
{  
  [Tool][GlobalClass, Icon("res://addons/rokojori_action_library/Icons/RemoveNode.svg")]
  public partial class RemoveNode : Action
  {
    [Export]
    public Node target;

    [Export]
    public bool queue = true;

    [Export]
    public bool disableAllNodes = true;


    protected override void _OnTrigger()
    {
      if ( target == null || Engine.IsEditorHint() )
      {
        return;
      }

      if ( ! IsInstanceValid( this ) || ! IsInstanceValid( target ) )
      {
        return;
      }

      CallDeferred( "SelfDestroy" );
      
    }

    void SelfDestroy()
    {
      if ( ! IsInstanceValid( target ) )
      {
        return;
      }

      if ( disableAllNodes )
      {
        target.ForEach<Node>( n => NodeState.Disable( n ) );
        NodeState.Disable( target );
      }

      target.SelfDestroy( queue );
    } 
  }
}