using UnityEngine;

namespace Streamingle.Utils.RoughConstraints
{
    [ExecuteAlways]
    [AddComponentMenu("Streamingle Utilities/Constraints/Rough Position Constraint")]
    public class RoughPositionConstraint : RoughConstraintBase
    {
        [Header("Position")]
        public Vector3Bool constrainedAxis = Vector3Bool.All;
        public Vector3 positionOffset;
        public bool offsetInSourceSpace = true;

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

            if (offsetInSourceSpace && sources.Count > 0 && sources[0].sourceTransform != null)
            {
                targetPosition += sources[0].sourceTransform.TransformVector(positionOffset);
            }
            else
            {
                targetPosition += positionOffset;
            }

            targetPosition = ApplyAxisMask(transform.position, targetPosition, constrainedAxis);
            transform.position = Vector3.Lerp(transform.position, targetPosition, followT * weight);
        }

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

            var delta = transform.position - sourcePosition;
            if (offsetInSourceSpace && sources.Count > 0 && sources[0].sourceTransform != null)
            {
                positionOffset = sources[0].sourceTransform.InverseTransformVector(delta);
            }
            else
            {
                positionOffset = delta;
            }
        }
    }
}
