
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System;
using Godot;


namespace Rokojori
{  
  [Tool]
  [GlobalClass, Icon("res://addons/rokojori_action_library/Icons/FollowCamera.svg") ]
  public partial class FollowCamera3D:VirtualCamera
  {
    [Export]
    public Node3D target;
    [Export]
    public float speed = 5;
    [Export]
    public float distance = 5; 
    [Export]
    public float rotationSmoothingCoefficient = 0.1f;

    Smoother smoother = new Smoother();

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

      var d = (float) delta;
      
      Move( d );
      Rotate( d );
    }

    void Move( float delta )
    {
      var direction = target.GlobalPosition - GlobalPosition;

      if ( direction.Length() > distance )
      { 
        var step = direction.Normalized() * speed * delta;  
        GlobalPosition += step;
      }
    }

    void Rotate( float delta )
    {
      var currentRotation = this.GlobalQuaternion();
      LookAt( target.GlobalPosition, Vector3.Up, true );
      var nextRotation = this.GlobalQuaternion();

      var smoothedRotation = smoother.SmoothWithCoefficient( currentRotation, nextRotation, rotationSmoothingCoefficient, delta );
      
      Math3D.SetGlobalRotationTo( this, smoothedRotation );
    }
  }
}