using UnityEngine;

namespace Streamingle.Utils.RoughConstraints
{
    [ExecuteAlways]
    [AddComponentMenu("Streamingle Utilities/Constraints/Rough Look At Constraint")]
    public class RoughLookAtConstraint : RoughConstraintBase
    {
        [Header("Look At")]
        public Vector3 forwardAxis = Vector3.forward;
        public Vector3 worldUpVector = Vector3.up;
        public Vector3 targetPositionOffset;
        public Vector3 rotationOffset;

        protected override void ExecuteConstraint(float followT)
        {
            if (!TryGetWeightedPosition(out var targetPosition))
            {
                return;
            }

            targetPosition += targetPositionOffset;
            var direction = targetPosition - transform.position;
            if (direction.sqrMagnitude < 0.000001f)
            {
                return;
            }

            var targetRotation = LookRotationForAxis(direction, worldUpVector, forwardAxis, Vector3.up);
            targetRotation *= Quaternion.Euler(rotationOffset);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, followT * weight);
        }

        protected override void CaptureOffsetsFromCurrentPose()
        {
            if (!TryGetWeightedPosition(out var targetPosition))
            {
                return;
            }

            targetPosition += targetPositionOffset;
            var direction = targetPosition - transform.position;
            if (direction.sqrMagnitude < 0.000001f)
            {
                return;
            }

            var baseRotation = LookRotationForAxis(direction, worldUpVector, forwardAxis, Vector3.up);
            rotationOffset = (Quaternion.Inverse(baseRotation) * transform.rotation).eulerAngles;
        }
    }
}
