
using System;
using Godot;


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

    [Export]
    public TweenParticlesData tweenParticlesData;

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

    [Export]
    public TimeLine timeLine;


    protected override void _OnTrigger()
    {
      // if ( Engine.IsEditorHint() )
      // {
      //   return;
      // }
      
      if ( particles3D == null )
      {
        return;
      }

      var tl = TimeLineManager.Ensure( timeLine );

      var start = tl.position;

       var fromData = new TweenParticlesData();
      fromData.CopyFrom( particles3D );
      var lerpData = tweenParticlesData.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( particles3D ) )
          {
            DispatchEnd( sequenceID );
            return;
          }

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

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

          TweenParticlesData.LerpTo( fromData, tweenParticlesData, state, lerpData );

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

  }
}