using System.Linq;
using Godot;
using Godot.Collections;

public partial class Player : CharacterBody3D
{
   [Export]
   private float _speed = 5.0f;
   [Export]
   private float _jumpVelocity = 4.5f;
   [Export]
   private float _sensitivityHorizontal = 0.05f;
   [Export]
   private float _sensitivityVertical = 0.05f;
   [Export]
   private float _joystickDeadZone = 0.5f;
   [Export]
   private Array<PackedScene> _projectiles;

   public bool CanShoot { get; private set; }

   private Node3D _cameraMount;
   private Node3D _pivot;
   private Node3D _camera;
   private PackedScene _weaponType;

   // Get the _gravity from the project settings to be synced with RigidBody nodes.
   public float _gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle();

   public override void _Ready()
   {
      Input.MouseMode = Input.MouseModeEnum.Captured;
      _cameraMount = GetNode<Node3D>("/root/Main/Player/CameraMount");
      _camera = GetNode<Node3D>("/root/Main/Player/CameraMount/Camera");
      _pivot = GetNode<Node3D>("/root/Main/Player/Pivot");
      _weaponType = _projectiles.First();
      CanShoot = true;
   }

   public override void _Process(double delta)
   {
      if (Input.IsActionJustPressed("quit"))
         GetTree().Quit();
      if (Input.IsActionJustPressed("shoot") && CanShoot)
         Shoot();
      if (Input.IsActionJustPressed("switch"))
         SwitchWeaponType();
   }

   public override void _PhysicsProcess(double delta)
   {
      var gravityDelta = _gravity * (float)delta;
      var velocity = CalculateMovement(Velocity, Transform, gravityDelta);

      Velocity = velocity;
      MoveAndSlide();
   }

   private async void Shoot()
   {
      GD.Print("Shoot");
      var projectile = _weaponType.Instantiate<Projectile>();
      projectile.Position = Position;
      projectile.Rotation = Rotation;
      GetParent().AddChild(projectile);
      CanShoot = false;
      await ToSignal(GetTree().CreateTimer(projectile.Cooldown), "timeout");
      CanShoot = true;
   }

   private async void SwitchWeaponType()
   {
      var index = _projectiles.IndexOf(_weaponType);
      _weaponType = _projectiles[(index + 1) % _projectiles.Count];
      CanShoot = false;
      await ToSignal(GetTree().CreateTimer(.5), "timeout");
      CanShoot = true;

   }

   private Vector3 CalculateMovement(Vector3 velocity, Transform3D transform, float gravityDelta)
   {
      if (!IsOnFloor())
         velocity.Y -= gravityDelta;

      if (Input.IsActionJustPressed("jump") && IsOnFloor())
         velocity.Y = _jumpVelocity;

      Vector2 inputDir = Input.GetVector("right", "left", "back", "forward");
      Vector3 direction = (transform.Basis * new Vector3(inputDir.X, 0, inputDir.Y)).Normalized();
      if (direction != Vector3.Zero)
      {
         velocity.X = direction.X * _speed;
         velocity.Z = direction.Z * _speed;
         GetNode<Node3D>("Pivot").LookAt(Position + direction.Normalized(), Vector3.Up);
      }
      else
      {
         velocity.X = Mathf.MoveToward(Velocity.X, 0, _speed);
         velocity.Z = Mathf.MoveToward(Velocity.Z, 0, _speed);
      }

      return velocity;
   }
}
