using System.Collections.Concurrent;
using JiShe.CollectBus.IoTDB.Interface;
using JiShe.CollectBus.IoTDB.Options;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;

namespace JiShe.CollectBus.IoTDB.Provider
{

    /// <summary>
    /// 实现带缓存的Session工厂
    /// </summary>
    public class IoTDbSessionFactory : IIoTDbSessionFactory, ISingletonDependency
    {
        private readonly IoTDbOptions _options;
        private readonly ConcurrentDictionary<bool, IIoTDbSessionPool> _pools = new();
        private bool _disposed;

        /// <summary>
        /// IoTDbSessionFactory
        /// </summary>
        /// <param name="options"></param>
        public IoTDbSessionFactory(IOptions<IoTDbOptions> options)
        {
            _options = options.Value;
        }

        public IIoTDbSessionPool GetSessionPool(bool useTableSession)
        {
            if (_disposed) throw new ObjectDisposedException(nameof(IoTDbSessionFactory));

            return _pools.GetOrAdd(useTableSession, key =>
            {
                var pool = key
                    ? (IIoTDbSessionPool)new TableSessionPoolAdapter(_options)
                    : new SessionPoolAdapter(_options);

                pool.OpenAsync().ConfigureAwait(false).GetAwaiter().GetResult(); ;
                return pool;
            });
        }

        public void Dispose()
        {
            foreach (var pool in _pools.Values)
            {
                pool.Dispose();
            }
            _pools.Clear();
            _disposed = true;
        }
    }
}
