
using System;
using Godot;


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

    [Export]
    public TweenLightData tweenLightData;

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

    [Export]
    public TimeLine timeLine;


    protected override void _OnTrigger()
    {
      if ( Engine.IsEditorHint() )
      {
        return;
      }

      if ( light3D == null || tweenLightData == null )
      {
        return;
      }

      var tl = TimeLineManager.Ensure( timeLine );

      var start = tl.position;

      var fromData = new TweenLightData();
      fromData.CopyFrom( light3D );
      var lerpData = tweenLightData.Clone( true );
      
      var sequenceID = DispatchStart(); 

      var tweenType = this.tweenType;

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

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

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

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

          TweenLightData.LerpTo( fromData, tweenLightData, state, lerpData );

          lerpData.CopyTo( light3D );
         
          if ( type == TimeLineSpanUpdateType.End )
          {          
            DispatchEnd( sequenceID );
          }
        },
        this
      );
    }

  }
}