using Godot;


namespace Rokojori
{  
  [Tool][GlobalClass ]
  public partial class MoveTo : SequenceAction, Animator
  {
    [Export]
    public Node3D target;

    [Export]
    public Node3D goal;

    [Export]
    public Duration duration;

    int _actionID = -1;
    int _currentSpanAnimationID = -1;

    public void OnAnimatorStart(){}
    public void OnAnimatorEnd(){}
    public void OnAnimatorCancel(){}

    protected override void _OnTrigger()
    {
      if ( _actionID != -1 )
      {
        CancelAction( _actionID );
      }

      var sequenceID = DispatchStart();
      _actionID = sequenceID; 

      AnimationManager.StartAnimation( this, target, AnimationMember.Position );

      var startPosition = target.GlobalPosition;
      
      _currentSpanAnimationID = TimeLineManager.ScheduleSpanIn( duration.timeLine, 0, duration.GetDurationInSeconds(), 
        ( TimeLineSpan span, TimeLineSpanUpdateType type )=>
        {     
          if ( span.id != _currentSpanAnimationID )
          {
            return;
          }
          
          if ( ! AnimationManager.IsAnimating( this, target, AnimationMember.Position ) )
          {
            return;
          }

          target.GlobalPosition = startPosition.Lerp( goal.GlobalPosition, span.phase );;


          if ( TimeLineSpanUpdateType.End == type )
          {
            AnimationManager.EndAnimation( this, target, AnimationMember.Position );

            DispatchEnd( sequenceID );
            return;
          }
        }
       ).id;
    }
  }
}