using UnityEngine;

namespace Streamingle.Utils.RoughConstraints
{
    [ExecuteAlways]
    [AddComponentMenu("Streamingle Utilities/Constraints/Rough Rotation Constraint")]
    public class RoughRotationConstraint : RoughConstraintBase
    {
        [Header("Rotation")]
        public Vector3Bool constrainedAxis = Vector3Bool.All;
        public Vector3 rotationOffset;

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

            targetRotation *= Quaternion.Euler(rotationOffset);
            var maskedEuler = ApplyEulerAxisMask(transform.rotation, targetRotation, constrainedAxis);
            targetRotation = Quaternion.Euler(maskedEuler);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, followT * weight);
        }

        protected override void CaptureOffsetsFromCurrentPose()
        {
            if (!TryGetWeightedRotation(out var sourceRotation))
            {
                return;
            }

            rotationOffset = (Quaternion.Inverse(sourceRotation) * transform.rotation).eulerAngles;
        }
    }
}
