
using Godot;


namespace Rokojori
{  
  [Tool][GlobalClass, Icon("res://addons/rokojori_action_library/Icons/SetNodeState.svg")]
  public partial class SetPhysicsState : Action
  {
    [Export]
    public PhysicsBody3D physicsBody;

    public enum PhysicsState
    {
      Physics_Enabled,
      Physics_Disabled
    }

    [Export]
    public PhysicsState state = PhysicsState.Physics_Disabled;

    [ExportGroup("Collisions")]
    
    [Export]
    public bool setCollisions = false;

    [ExportToolButton( "Clear Collisions" )]
    public Callable clearCollisionsButton => Callable.From(
      ()=>
      {
        collisionLayer = 0;
        collisionMask = 0; 
      }
    );

    [ExportToolButton( "Copy Collisions From Physics Body" )]
    public Callable copyCollisionsButton => Callable.From(
      ()=>
      {
        collisionLayer = physicsBody.CollisionLayer;
        collisionMask = physicsBody.CollisionMask; 
      }
    );

    [Export(PropertyHint.Layers2DPhysics)]
    public uint collisionLayer = 0;

    [Export(PropertyHint.Layers2DPhysics)]
    public uint collisionMask = 0;

    

    protected override void _OnTrigger()
    {
      CallDeferred( "SetStates" );
    }

    void SetStates()
    {
      var enbled = state == PhysicsState.Physics_Enabled;
      var trillian = enbled ? Trillean.True : Trillean.False;

      NodeState.Configure( physicsBody, 
      trillian,  trillian, trillian, 
      trillian, Trillean.Any, false, ProcessModeEnum.Inherit );

      if ( physicsBody is RigidBody3D rb )
      {
        rb.Freeze = ! enbled;        
      }

      if ( setCollisions )
      {     
        physicsBody.CollisionLayer = collisionLayer;
        physicsBody.CollisionMask = collisionMask;
      }
      
    }
  }

}