using System;
using System.Collections.Generic;
using XGame.Framework.Memory;

namespace XGame.Framework
{
    /// <summary>
    /// List缓存池
    /// * 非线程安全
    /// </summary>
    public static partial class ListPool
    {
        static readonly Dictionary<Type, Stack<object>> pool = new();

        const int CACHE_LIMIT = 32;

        internal static void Initialize()
        {
            MemoryMonitor.Register(Clear);
        }
        internal static void Dispose()
        {
            pool.Clear();
            MemoryMonitor.UnRegister(Clear);
        }
        public static void Clear()
        {
            pool.Clear();
        }
        public static List<T> Acquire<T>()
        {
            Type type = typeof(T);
            if (pool.ContainsKey(type))
            {
                var stack = pool[type];
                if (stack.Count > 0)
                    return stack.Pop() as List<T>;
            }
            return new List<T>();
        }
        public static void Recycle<T>(List<T> list)
        {
            if ( list == null)
            {
                return;
            }
            Type type = typeof(T);
            if (!pool.TryGetValue(type, out var stack))
            {
                stack = new Stack<object>();
                pool.Add(type, stack);
            }
            list.Clear();

            if (stack.Count >= CACHE_LIMIT)
                stack.Clear();
            else if (stack.Contains(list))
            {
                Log.Error($"ObjectPool.Recycle 重复回收, type: {type.FullName}");
                return;
            }
            stack.Push(list);
        }
    }
}
