
using System;
using Godot;


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

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

    [Export]
    public bool cacheEndPositionOnStart = true;

    [Export]
    public TimeLine timeLine;


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

      var tl = TimeLineManager.Ensure( timeLine );

      var start = tl.position;

      var fromWeight =  activeVolume.weight;
      var toWeight = endWeight;

      var sequenceID = DispatchStart(); 

      var tweenType = this.tweenType;

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

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

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

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

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

          var lerpedWeight = Mathf.Lerp( fromWeight, toWeight, state );

          activeVolume.weight = lerpedWeight;

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

  }
}