
using Godot;
using System.Collections.Generic;

namespace Rokojori
{  
  [Tool][GlobalClass]
  public partial class VelocityToSound:Action
  {
    [Export]
    public PhysicsBody3D velocitySource;

    [Export]
    public AudioStreamPlayer3D target;

    [Export]
    public Curve velocityToVolumeLinear;

    [Export]
    public Curve velocityToPitchScale;    

    [Export]
    public Smoothing velocitySmoothing;

    [Export]
    public float inAirMultiply = 0f;

    [Export]
    public bool ensurePlaying = true;



    public override void _Process( double delta )
    {
      if ( velocitySource == null || target == null )
      {
        return;
      }

      var velocity = Smoothing.Apply( velocitySmoothing, velocitySource.GetVelocity().Length(), (float) delta );

      if ( velocitySource.IsInAir() )
      {
        velocity *= inAirMultiply;
      }


      var amp = velocityToVolumeLinear == null ? 1 : velocityToVolumeLinear.Sample( velocity );
      var pitch = velocityToPitchScale == null ? 1 : velocityToPitchScale.Sample( velocity );

      // if ( velocity == 0 )
      // {
      //   this.LogInfo( "Velocity == 0" );
      // }

      // if ( velocity != 0 )
      // {
      //   this.LogInfo( "Velocity != 0" );
      // }

      // this.LogInfo( "Vel:", (int)(velocity), "Amp:", (int)(amp * 100 ) + "%",(int) (pitch * 100) );

      if ( ensurePlaying && amp > 0 && ! target.Playing )
      {
        target.Playing = true;
      }

      target.VolumeLinear = amp;
      target.PitchScale = pitch;
    }
  }

}