
using System;
using Godot;


namespace Rokojori
{  
  [Tool]
  [GlobalClass, Icon("res://addons/rokojori_action_library/Icons/Tween.svg")]
  public partial class TweenCompositorVFX:SequenceAction, Animator
  { 
    [Export]
    public CompositorVFX compositorVFX;

    [Export]
    public float endValue;

    [Export]
    public Duration duration;

    [Export]
    public Curve curve;

    [ExportGroup( "Editor Testing")]
    [Export]
    public bool forceStartValue = false;
    
    [Export]
    public float forcedStartValue = 0f;

    public void OnAnimatorStart(){}
    public void OnAnimatorEnd(){}
    public void OnAnimatorCancel(){}

    int _actionID = -1;
    int _timeID = -1;


    

    protected override void _OnTrigger()
    {
      this.LogInfo( "Started Float Tween" );
      

      // if ( Engine.IsEditorHint() )
      // {
      //   return;
      // }

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

      _actionID = DispatchStart();
      

      var startValue = compositorVFX.driverValue;

      if ( forceStartValue && Engine.IsEditorHint() )
      { 
        startValue = forcedStartValue;
      }
      
     

      AnimationManager.StartAnimation( this, compositorVFX, "driverValue" );

      _timeID = TimeLineManager.ScheduleSpanWith( duration,
        ( span, type )=>
        {         

          // this.LogInfo( "Update Float Tween", startValue );
          if ( span.id != _timeID )
          {
            return;
          }

          if ( ! AnimationManager.IsAnimating( this, compositorVFX, "driverValue" ) )
          {
            return;
          }

          var phase = span.phase;

          if ( curve != null )
          {
            phase = curve.Sample( phase );
          }

          var value = Mathf.Lerp( startValue, endValue, phase );

          compositorVFX.driverValue = value;

          if ( type == TimeLineSpanUpdateType.End )
          {   
            compositorVFX.driverValue = value; 
            AnimationManager.EndAnimation( this, compositorVFX, "driverValue"  );
            DispatchEnd( _actionID );
            _actionID = -1;
            _timeID = -1;
          }
        },

        this
      ).id;
    }

  }
}