using System.Collections.Generic;
using UnityEngine;

namespace NBF
{
    public static class VerletPhysics
    {
        private static List<VerletRope> ropeGenerators = new List<VerletRope>();
        
        public static void RegisterRopeGenerator(VerletRope generator)
        {
            if (!ropeGenerators.Contains(generator))
            {
                ropeGenerators.Add(generator);
            }
        }
        public static void UnregisterRopeGenerator(VerletRope generator)
        {
            if (ropeGenerators.Contains(generator))
            {
                ropeGenerators.Remove(generator);
            }
        }

       
        
        public static bool Raycast(Ray ray, out RopeHitInfo hitInfo, float maxDistance)
        {
            var closestHitDistance = float.MaxValue;
            var isHit = false;
            RopeHitInfo tempHitInfo = default;
            foreach (var generator in ropeGenerators)
            {
                if (generator.Raycast(ray, out var hit, maxDistance))
                {
                    if (hit.Distance >= closestHitDistance) continue;
                    closestHitDistance = hit.Distance;
                    tempHitInfo = hit;
                    isHit = true;
                }
            }

            if (isHit)
            {
                hitInfo = tempHitInfo;
                return true;
            }
            hitInfo = default;
            return false;
        }
        public static bool Raycast(Ray ray, out RopeHitInfo hitInfo, float maxDistance, VerletRope exclude)
        {
            var closestHitDistance = float.MaxValue;
            var isHit = false;
            RopeHitInfo tempHitInfo = default;
            foreach (var generator in ropeGenerators)
            {
                if (generator == exclude) continue;
                if (generator.Raycast(ray, out var hit, maxDistance))
                {
                    if (hit.Distance >= closestHitDistance) continue;
                    closestHitDistance = hit.Distance;
                    tempHitInfo = hit;
                    isHit = true;
                }
            }
            if (isHit)
            {
                hitInfo = tempHitInfo;
                return true;
            }
            hitInfo = default;
            return false;
        }
    }
}