using System;
using System.Collections.Generic;

namespace WS
{
    ///<summary>内存数据对象池</summary>
    public class ObjectPool : WSComponent
    {
        ///<summary>对象池容器</summary>
        private readonly Dictionary<Type, ComponentQueue> dictionary = new Dictionary<Type, ComponentQueue>();

        ///<summary>取回</summary>
        public WSComponent Fetch(Type type)
        {
            WSComponent obj;
            if (!dictionary.TryGetValue(type, out ComponentQueue queue))
            {
                obj = (WSComponent)Activator.CreateInstance(type);
            }
            else if (queue.Count == 0)
            {
                obj = (WSComponent)Activator.CreateInstance(type);
            }
            else
            {
                obj = queue.Dequeue();
            }
            obj.Parent = null;
            obj.IsFromPool = true;//表记是从对象池创建
            return obj;
        }

        ///<summary>取回</summary>
        public T Fetch<T>() where T : WSComponent
        {
            T t = (T)Fetch(typeof(T));
            return t;
        }

        ///<summary>回收</summary>
        public void Recycle(WSComponent obj)
        {
            obj.Parent = this;
            Type type = obj.GetType();
            ComponentQueue queue;
            if (!dictionary.TryGetValue(type, out queue))
            {
                queue = new ComponentQueue(type.Name);
                queue.Parent = this;
                dictionary.Add(type, queue);
            }
            queue.Enqueue(obj);
        }

        ///<summary>清空</summary>
        public void Clear()
        {
            foreach (var kv in dictionary)
            {
                kv.Value.IsFromPool = false;
                kv.Value.Dispose();
            }
            dictionary.Clear();
        }
    }
}