using Godot;
using System.Collections;
using System.Collections.Generic;
using Godot.Collections;

namespace Rokojori
{
  [Tool]
  [GlobalClass, Icon("res://addons/rokojori_action_library/Icons/CCGravity.svg")]
  public partial class AddImpactForce:Action
  {
    [Export]
    public ImpactForce impactForce;

    [Export]
    public ImpactForces target;

    [Export]
    public OnCollision collisionDirectionSource;

    protected override void _OnTrigger()
    {
      this.LogInfo( TimeLine.osTime  );

      if ( target == null || impactForce == null )
      {
        return;
      }

      var colliders = collisionDirectionSource.GetNodesInside().FilterType<Node,Node3D>();

      var force = (ImpactForce) impactForce.Duplicate();

      if ( colliders.Count == 0 )
      {
        force.direction = target.controller.body.GlobalForward() * -1;
      }
      else
      {
        var positions = colliders.Map( c => c.GlobalPosition );
        var center = Math3D.ComputeAverage( positions );
        force.direction = target.controller.body.GlobalPosition - center;
      }

      force.direction = force.direction * new Vector3( 1, 0, 1 );

      this.LogInfo( force.direction );
      target.AddImpactForce( force );
    }


  }
}