using UnityEngine;

namespace NBF
{
    [RequireComponent(typeof(LineRenderer))]
    public class SimpleRope : MonoBehaviour
    {
        [Header("Endpoints")]
        [SerializeField] private Transform startPoint;
        [SerializeField] private Transform endPoint;

        [Header("Line")]
        [Min(0f)]
        [SerializeField] private float lineWidth = 0.01f;

        private LineRenderer lineRenderer;

        private void Awake()
        {
            lineRenderer = GetComponent<LineRenderer>();
            lineRenderer.positionCount = 2;
            ApplyWidth();
        }

        private void OnValidate()
        {
            if (lineWidth < 0f)
            {
                lineWidth = 0f;
            }

            if (lineRenderer == null)
            {
                lineRenderer = GetComponent<LineRenderer>();
            }

            if (lineRenderer != null)
            {
                lineRenderer.positionCount = 2;
                ApplyWidth();
            }
        }

        private void Update()
        {
            if (lineRenderer == null || startPoint == null || endPoint == null)
            {
                return;
            }

            lineRenderer.SetPosition(0, startPoint.position);
            lineRenderer.SetPosition(1, endPoint.position);
        }

        private void ApplyWidth()
        {
            lineRenderer.startWidth = lineWidth;
            lineRenderer.endWidth = lineWidth;
        }
    }
}
