
using System;
using Godot;


namespace Rokojori
{  
  [Tool]
  [GlobalClass, Icon("res://addons/rokojori_action_library/Icons/Tween.svg")]
  public partial class TweenScale:SequenceAction
  {
    [Export]
    public Node3D target;

    [Export]
    public Vector3 endScale = Vector3.One;    

    [Export]
    public TweenType tweenType = new TweenTimeCurve();

    [Export]
    public bool cacheEndPositionOnStart = true;

    [Export]
    public TimeLine timeLine;


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

      var tl = TimeLineManager.Ensure( timeLine );

      var start = tl.position;

      var fromScale =  target.Scale;
      var toScale = endScale;

      var sequenceID = DispatchStart(); 

      var tweenType = this.tweenType;

      if ( tweenType == null )
      {
        tweenType = TweenTimeCurve.defaultCurve;
      }      

      TimeLineManager.ScheduleSpanIn( tl, 0, tweenType.GetTweenDuration(), 
        ( span, type )=>
        {         
          if ( ! GodotObject.IsInstanceValid( target ) )
          {
            DispatchEnd( sequenceID );
            return;
          }

          var timeNow = tl.position;
          var elapsed = timeNow - start;

          var state = tweenType.GetTweenPhaseForPhase( span.phase );

          if ( ! cacheEndPositionOnStart )
          {
            var toScale = endScale;
          }

          var lerpedScale = fromScale.Lerp( toScale, state );

          target.Scale = lerpedScale;

          if ( type == TimeLineSpanUpdateType.End )
          {          
            DispatchEnd( sequenceID );
          }
        }
      );
    }

  }
}