using System;
using System.Collections.Concurrent;
using SqlSugar;

namespace DB.Database
{
    public interface ISqlSugarProvider
    {
        ISqlSugarClient GetClient();
        ISqlSugarClient GetClientStr(string connectionString);
    }

    public class SqlSugarProvider : ISqlSugarProvider, IDisposable
    {
        private readonly string _connectionString;
        private readonly SqlSugarScope _rootScope;
        private readonly ConcurrentDictionary<string, SqlSugarScope> _rootScopes
            = new ConcurrentDictionary<string, SqlSugarScope>();

        public SqlSugarProvider(string connectionString)
        {
            _connectionString = connectionString;
            _rootScope = BuildRootScope(connectionString);
        }

        private static SqlSugarScope BuildRootScope(string connStr)
        {
            var config = new ConnectionConfig()
            {
                ConnectionString = connStr,
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            };
            return new SqlSugarScope(config);
        }

        public ISqlSugarClient GetClient()
        {
            return _rootScope.CopyNew();
        }

        public ISqlSugarClient GetClientStr(string connectionString)
        {
            var root = _rootScopes.GetOrAdd(connectionString, BuildRootScope);
            return root.CopyNew();
        }

        public void Dispose()
        {
            _rootScope?.Dispose();
            foreach (var scope in _rootScopes.Values)
            {
                scope?.Dispose();
            }
        }
    }
}
