
using Godot;


namespace Rokojori
{  
  [Tool]
  [GlobalClass ]
  public partial class CountNumber : SequenceAction
  {
    [Export]
    public UIText target;

    [Export]
    public int startValue = 0;

    [Export]
    public int endValue = 100;

    int _actionID = -1;
    int _animationID = -1;

    [Export]
    public Duration duration;

    protected override void _OnTrigger()
    {      
      if ( target == null )
      {
        return;
      }

      if ( _actionID != -1 )
      {
        CancelAction( _actionID );
      }


      var _id = DispatchStart();

      _actionID = _id;

      _animationID = TimeLineManager.ScheduleSpanWith( duration,
        ( s, t ) => 
        {
          if ( _animationID != s.id )
          {
            return;
          }

          var number = startValue + s.phase * ( endValue - startValue );
          var intNumber = Mathf.RoundToInt( number );

          target.Set( intNumber + "" );

          if ( TimeLineSpanUpdateType.End == t )
          {
            target.Set( endValue + "" );
            DispatchEnd( _id );
          }
        }
      ).id;

    }
  }
}