using System.Collections.Generic;

namespace Raycast.Win32
{
    public interface IRecyclable
    {
        void Recycle();
    }

    public static class RecyclePool<T> where T : IRecyclable, new()
    {
        private static IReadOnlyList<T> Collection;

        private static int Capacity;
        private static int Index;

        public static void Init(int capacity)
        {
            if (Collection != null && Capacity != capacity)
            {
                foreach (var item in Collection)
                {
                    item.Recycle();
                }
            }
            Capacity = capacity;
            Index = default;
            var list = new List<T>(capacity);
            for (var i = 0; i < capacity; i++)
            {
                list.Add(new T());
            }
            Collection = list.AsReadOnly();
        }

        public static T Get()
        {
            var instance = Collection[Index];
            instance.Recycle();
            Index++;
            if (Index >= Capacity)
                Index = default;
            return instance;
        }
    }
}