
using System;
using Godot;


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

    [Export]
    public float endVolume = 0;

    public enum VolumeUnit
    {
      Linear,
      Decibel
    }

    [Export]
    public VolumeUnit volumeUnit = VolumeUnit.Linear;  

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

    [Export]
    public bool cacheEndPositionOnStart = true;

    [Export]
    public TimeLine timeLine;


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

      var tl = TimeLineManager.Ensure( timeLine );

      var start = tl.position;

      var fromVolume = target.VolumeDb;
      var toVolume = volumeUnit == VolumeUnit.Linear ? MathAudio.AmplitudeToDecibels( endVolume ) : endVolume;

      var sequenceID = DispatchStart(); 

      var tweenType = this.tweenType;

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

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

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

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

          if ( ! cacheEndPositionOnStart )
          {
            var toScale = volumeUnit == VolumeUnit.Linear ? MathAudio.AmplitudeToDecibels( endVolume ) : endVolume;;
          }

          var lerpedVolume = Mathf.Lerp( fromVolume, toVolume, state );

          target.VolumeDb = lerpedVolume;

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

  }
}