using Engine.Scene.Component.BuiltIn;
using OpenTK.Mathematics;

namespace DoomDeathmatch.Component.Util;

public class BillboardComponent : Engine.Scene.Component.Component
{
  public Transform? Target { get; set; }
  public Vector3 Up { get; set; } = Vector3.UnitZ;

  public override void Update(double parDeltaTime)
  {
    if (Target == null)
    {
      return;
    }

    var targetPosition = Target.GetFullTranslation();
    var currentPosition = GameObject.Transform.GetFullTranslation();

    var forward = targetPosition - currentPosition;
    forward -= Vector3.Dot(forward, Up) * Up;
    if (forward.LengthSquared > 0)
      forward.Normalize();

    var right = Vector3.Cross(Up, forward);
    if (right.LengthSquared > 0)
      right.Normalize();

    var recalculatedUp = Vector3.Cross(forward, right).Normalized();

    var rotationMatrix = new Matrix3(
      right.X, recalculatedUp.X, forward.X,
      right.Y, recalculatedUp.Y, forward.Y,
      right.Z, recalculatedUp.Z, forward.Z
    );

    GameObject.Transform.Rotation = Quaternion.FromMatrix(rotationMatrix);
  }
}