
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;
using Azure.Messaging.ServiceBus;

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

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

        public ServiceBusClient GetServiceBusClient(string name = "Default")
        {           
            try
            {
                var client = ServiceBusClients.GetOrAdd(name, x => new ServiceBusClient(_optionsMonitor.Get(name).ServiceBusConnectionString));               
                return client;
            }
            catch (OptionsValidationException e)
            {
                _logger?.LogWarning(e, e.Message);
                return null;
            }
        }       
    }
}
