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 ImpactForces:CharacterControllerAction
  {

    List<ImpactForce> _forces = new List<ImpactForce>();
    List<float> _forcePosition = new List<float>();

    public void AddImpactForce( ImpactForce impactForce )
    {
      _forces.Add( impactForce );
      _forcePosition.Add( 0 );
    }


    protected override void _OnTrigger()
    {
      if ( _forces.Count == 0 )
      { 
        return;
      }


      var combinedForce = Vector3.Zero;

      var removals = new List<int>();

      var currentVelocity = body.Velocity * controller.delta;

      var maxFreeze = 1f;

      for ( int i = 0; i < _forces.Count; i++ )
      {        

        var position = _forcePosition[ i ];
        var duration = _forces[ i ].duration;

        if ( position > duration )
        {
          position = duration;
          removals.Add( i );
        }

        var force  = _forces[ i ].forceOverTime.Sample( position ) * _forces[ i ].maxForce;
        var freeze = 1f - _forces[ i ].freezeOverTime.Sample( position ); 

        maxFreeze = Mathf.Min( freeze, maxFreeze );

        combinedForce += force * _forces[ i ].direction;

        _forcePosition[ i ] += controller.delta;

        
      }
      
      _forces.RemoveIncreasingSortedIndices( removals );
      _forcePosition.RemoveIncreasingSortedIndices( removals );

      // this.LogInfo( combinedForce );
      SetVelocity( combinedForce + currentVelocity * maxFreeze );
    }
  }
}