
using System;
using Godot;


namespace Rokojori
{  
  [Tool]
  [GlobalClass ]
  public partial class TweenTimeLineSpeed:SequenceAction
  {
    [Export]
    public TimeLine targetTimeLine;

    [Export]
    public float timeLineSpeed;

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

    [Export]
    public bool cacheSpeedOnStart = true;

    [Export]
    public TimeLine tweenTimeLine;

    protected override void _OnTrigger()
    {
      if ( targetTimeLine == null )
      {
        return;
      }
      
      var tl = tweenTimeLine == null ? TimeLineManager.Get().realtimeTimeline : tweenTimeLine;

      var start = targetTimeLine.position;

      var fromSpeed = targetTimeLine.runner.speed;
      var toSpeed = timeLineSpeed;

      
      var sequenceID = DispatchStart(); 

      var tweenType = this.tweenType;

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

      TimeLineManager.ScheduleSpanIn( tl, 0, tweenType.GetTweenDuration(), 
        ( span, type )=>
        {         
          var timeNow = tl.position;
          var elapsed = timeNow - start;

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

          if ( ! cacheSpeedOnStart )
          {
            toSpeed = timeLineSpeed;
          }

          var lerpedSpeed = Mathf.Lerp( fromSpeed, toSpeed, state );

          targetTimeLine.runner.speed = lerpedSpeed;
         
          if ( type == TimeLineSpanUpdateType.End )
          {          
            DispatchEnd( sequenceID );
          }
        }
      );
    }

  }
}