using log4net;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 对象池管理器
    /// </summary>
    public class ObjectPoolManager : IObjectPoolManager
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly static ILog log = LogManager.GetLogger(typeof(ObjectPoolManager));

        /// <summary>
        /// 对象池列表
        /// </summary>
        private readonly ConcurrentDictionary<string, WeakReference> pool = new ConcurrentDictionary<string, WeakReference>();

        /// <summary>
        /// 添加对象
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="obj">对象</param>
        /// <returns>是否成功添加</returns>
        public bool Add(string key, object obj)
        {
            if (pool.ContainsKey(key))
                return false;

            WeakReference reference = new WeakReference(obj, false);
            return pool.TryAdd(key, reference);
        }

        /// <summary>
        /// 销毁
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>是否成功销毁</returns>
        public bool Dispose(string key)
        {
            try
            {

                if (!pool.ContainsKey(key))
                    return false;

                if (!pool.TryRemove(key, out WeakReference reference))
                    return false;

                object obj = reference.Target;
                if (obj == null)
                    return true;

                IDisposable disposable = obj as IDisposable;
                if (disposable == null)
                    return true;

                disposable.Dispose();

                return true;
            }
            catch (Exception ex)
            {
                log.Error(ex);

                return false;
            }
        }

        /// <summary>
        /// 销毁所有的对象
        /// </summary>
        public void DisposeAll()
        {
            List<WeakReference> list = pool.Values.ToList();
            pool.Clear();
            foreach (var item in list)
            {
                try
                {

                    if (item == null || item.Target == null)
                        continue;

                    IDisposable disposable = item.Target as IDisposable;
                    if (disposable == null)
                        continue;

                    disposable.Dispose();
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
    }
}
