using OpenTK.Mathematics;

namespace DoomDeathmatch.Component.Util;

public class GravityComponent : Engine.Scene.Component.Component
{
  public float Strength { get; set; } = 10.0f;

  public Vector3 Direction
  {
    get => _direction;
    set => _direction = value.Normalized();
  }

  public float Floor { get; set; } = 5.0f;

  public bool IsInAir { get; private set; } = false;

  private RigidbodyComponent _rigidbody = null!;
  private Vector3 _direction = -Vector3.UnitZ;

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

    ArgumentNullException.ThrowIfNull(_rigidbody);
  }

  public override void Update(double parDeltaTime)
  {
    var heightAlongDirection = Vector3.Dot(GameObject.Transform.Translation, Direction);
    if (heightAlongDirection > Floor)
    {
      IsInAir = false;
      var velocityAlongDirection = Vector3.Dot(_rigidbody.Velocity, Direction);
      if (velocityAlongDirection > 0)
        _rigidbody.AddVelocity(-velocityAlongDirection * Direction);

      return;
    }

    IsInAir = true;
    var gravity = Strength * Direction;
    _rigidbody.AddForce(gravity);
  }
}