using Engine.Input;
using OpenTK.Mathematics;

namespace DoomDeathmatch.Component;

public class ControllerComponent : Engine.Scene.Component.Component
{
  public float Speed { get; set; } = 10.0f;
  public float RotationSpeed { get; set; } = 70.0f;

  private readonly IInputHandler _inputHandler = Engine.Engine.Instance.InputHandler!;
  private RigidbodyComponent _rigidbody;

  public override void Awake()
  {
    _rigidbody = GameObject.GetComponent<RigidbodyComponent>()!;
  }

  public override void Update(double parDeltaTime)
  {
    var movement = Vector3.Zero;
    var rotation = 0.0f;

    if (_inputHandler.IsKeyPressed(KeyboardButtonCode.W))
      movement.Y += 1;
    if (_inputHandler.IsKeyPressed(KeyboardButtonCode.S))
      movement.Y -= 1;
    if (_inputHandler.IsKeyPressed(KeyboardButtonCode.D))
      movement.X += 1;
    if (_inputHandler.IsKeyPressed(KeyboardButtonCode.A))
      movement.X -= 1;

    if (_inputHandler.IsKeyPressed(KeyboardButtonCode.Q))
      rotation += RotationSpeed;
    if (_inputHandler.IsKeyPressed(KeyboardButtonCode.E))
      rotation -= RotationSpeed;

    if (movement.LengthSquared > 0)
    {
      movement.Normalize();
      movement = GameObject.Transform.Rotation * movement;

      _rigidbody.AddVelocity(Speed * movement);
    }

    var velocityXy = _rigidbody.Velocity.Xy;
    if (velocityXy.LengthSquared > Speed * Speed)
    {
      var length = velocityXy.Length;
      _rigidbody.AddVelocity(new Vector3(-(length - Speed) / length * velocityXy));
    }

    GameObject.Transform.Rotation *= Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(rotation) *
                                                                             (float)parDeltaTime);
  }
}