
using Microsoft.Azure.Cosmos.Table;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using StackExchange.Redis;
using System.Collections.Concurrent;

namespace TEAMModelOS.SDK.DI
{
    public class AzureRedisFactory
    {
        private readonly IServiceProvider _services;
        private readonly IOptionsMonitor<AzureRedisFactoryOptions> _optionsMonitor;
        private readonly ILogger _logger;
        private ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionMultiplexers { get; } = new ConcurrentDictionary<string, ConnectionMultiplexer>();
        public AzureRedisFactory(IServiceProvider services, IOptionsMonitor<AzureRedisFactoryOptions> optionsMonitor, ILogger<AzureRedisFactory> logger)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));

            _services = services;
            _optionsMonitor = optionsMonitor;
            _logger = logger;
        }

        public IDatabase GetRedisClient( int dbnum = -1,string name = "Default")
        {           
            try
            {
                var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
                return cm.GetDatabase(dbnum);
            }
            catch (OptionsValidationException e)
            {
                _logger?.LogWarning(e, e.Message);
                return null;
            }
        }
        //public (IDatabase db , IServer server ) GetRedisDbCmClient(int dbnum = -1, string name = "Default")
        //{
        //    try
        //    {
        //        var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
                
        //        return (cm.GetDatabase(dbnum),cm.GetServer(cm.GetEndPoints()[0]));
        //    }
        //    catch (OptionsValidationException e)
        //    {
        //        _logger?.LogWarning(e, e.Message);
        //        return (null,null);
        //    }
        //}
    }
}
