using OpenTK.Mathematics;

namespace Engine.Scene.Component.BuiltIn;

public class Transform : Component
{
  private Vector3 _translation = Vector3.Zero;
  private Quaternion _rotation = Quaternion.Identity;
  private Vector3 _scale = Vector3.One;
  private Vector3 _size = Vector3.One;

  public ref Vector3 Translation => ref _translation;
  public ref Quaternion Rotation => ref _rotation;
  public ref Vector3 Scale => ref _scale;
  public ref Vector3 Size => ref _size;

  public Matrix4 LocalTransformMatrix => Matrix4.CreateScale(Scale) *
                                         Matrix4.CreateFromQuaternion(Rotation) *
                                         Matrix4.CreateTranslation(Translation);

  public Matrix4 TransformMatrix => LocalTransformMatrix * ParentTransformMatrix;

  public Matrix4 FullTransformMatrix => Matrix4.CreateScale(Size) * TransformMatrix;

  private Matrix4 ParentTransformMatrix
  {
    get
    {
      var parent = GameObject.Scene?.Hierarchy.GetParent(GameObject);
      return parent == null ? Matrix4.Identity : parent.Transform.TransformMatrix;
    }
  }

  public Vector3 GetFullTranslation()
  {
    return FullTransformMatrix.ExtractTranslation();
  }

  public Transform Clone()
  {
    var clone =
      new Transform { Translation = Translation, Rotation = Rotation, Scale = Scale, Size = Size };

    return clone;
  }

  public float SquaredDistanceTo(Transform parTransform)
  {
    var translation = GetFullTranslation();
    var otherTranslation = parTransform.GetFullTranslation();

    var difference = translation - otherTranslation;
    var squaredDistance = difference.LengthSquared;

    return squaredDistance;
  }
}