using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace TFramework
{
    public class ReferencePool
    {
        private Queue<IReference> _referencePool;

        private int _capacity = 100;

        public ReferencePool(int capacity)
        {
            _capacity = capacity;
            _referencePool = new Queue<IReference>(_capacity);
        }

        /// <summary>
        /// 引用数量
        /// </summary>
        public int Count => _referencePool.Count;

        /// <summary>
        /// 生成引用
        /// </summary>
        /// <returns></returns>
        public T Spawn<T>() where T : class, IReference, new() => Count > 0 ? _referencePool.Dequeue() as T : new T();

        /// <summary>
        /// 回收引用
        /// </summary>
        /// <param name="refe"></param>
        public void Recycle<T>(T refe) where T : class, IReference, new()
        {
            if (Count >= _capacity)
                refe = null;
            else
            {
                refe.Reset();
                _referencePool.Enqueue(refe);
            }
        }

        /// <summary>
        /// 清空所有引用
        /// </summary>
        public void Clear() => _referencePool.Clear();
    }
}
