using Godot;

public partial class CameraSystem : SpringArm3D
{
   [Export]
   private float _sensitivityHorizontal = 0.05f;
   [Export]
   private float _sensitivityVertical = 0.05f;
   [Export]
   private float _joystickDeadZone = 0.5f;

   private Node3D _pivot;
   private CharacterBody3D _characterBody;

   public override void _Ready()
   {
      _pivot = GetNode<Node3D>("/root/Main/Player/Pivot");
      _characterBody = GetNode<CharacterBody3D>("/root/Main/Player");
   }

   public override void _Process(double delta)
   {
      var joyRightX = Input.GetJoyAxis(0, JoyAxis.RightX);
      var joyRightY = Input.GetJoyAxis(0, JoyAxis.RightY);

      if (Mathf.Abs(joyRightX) > _joystickDeadZone)
      {
         var rotateAmount = joyRightX * _sensitivityHorizontal;
         _characterBody.RotateY(-rotateAmount);
         _pivot.RotateY(rotateAmount);
      }

      if (Mathf.Abs(joyRightY) > _joystickDeadZone)
      {
         RotateX(joyRightY * _sensitivityVertical);
         Rotation = new Vector3(Mathf.Clamp(Rotation.X, -0.7f, 0.7f), Rotation.Y, Rotation.Z);
      }
   }

   public override void _Input(InputEvent @event)
   {
      if (@event is InputEventMouseMotion mouseMotion)
      {
         _characterBody.RotateY(Mathf.DegToRad(-mouseMotion.Relative.X * _sensitivityHorizontal));
         _pivot.RotateY(Mathf.DegToRad(mouseMotion.Relative.X * _sensitivityHorizontal));
         RotateX(Mathf.DegToRad(mouseMotion.Relative.Y * _sensitivityVertical));
         Rotation = new Vector3(Mathf.Clamp(Rotation.X, -0.7f, 0.7f), Rotation.Y, Rotation.Z);
      }
   }
}
