using DoomDeathmatch.Component.MVC.Controller;
using Engine.Input;
using OpenTK.Mathematics;

namespace DoomDeathmatch.Component.Util;

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

  private readonly IInputHandler _inputHandler = Engine.Engine.Instance.InputHandler!;
  private MovementController _movementController = null!;

  public override void Awake()
  {
    _movementController = GameObject.GetComponent<MovementController>()!;

    ArgumentNullException.ThrowIfNull(_movementController);
  }

  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;

      _movementController.ApplyMovement(movement);
    }

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