using System.Collections.Concurrent;
using LogViewer.Core;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace MsLogger.Core;

public class DataStoreLoggerProvider: ILoggerProvider
{

    #region Constructor
    
    public DataStoreLoggerProvider(IOptionsMonitor<DataStoreLoggerConfiguration> config, ILogDataStore dataStore)
    {
        DataStore = dataStore;
        _currentConfig = config.CurrentValue;
        OnChangeToken = config.OnChange(updatedConfig => _currentConfig = updatedConfig);
    }

    #endregion

    #region fields
    
    private DataStoreLoggerConfiguration _currentConfig;

    private  IDisposable? OnChangeToken { get; }
    protected  ILogDataStore DataStore { get; }

    protected  ConcurrentDictionary<string, DataStoreLogger> Loggers { get; } = new();
    
    #endregion

    #region Methods
    
    public ILogger CreateLogger(string categoryName)
        => Loggers.GetOrAdd(categoryName, name => new DataStoreLogger(name, GetCurrentConfig, DataStore));

    protected DataStoreLoggerConfiguration GetCurrentConfig()
        => _currentConfig;

    public void Dispose()
    {
        GC.SuppressFinalize(this);
        Loggers.Clear();
        OnChangeToken?.Dispose();
    } 

    #endregion
}