using System;
using common;
using Microsoft.Extensions.Logging;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace eagle {
    // Customized ILoggerProvider, writes logs to text files
    public class CustomFileLoggerProvider : ILoggerProvider {
        private const string FileName = "ConnectionLogger";
        private static readonly Logger SharedLogger = Logger.GetLogger(FileName);

        public CustomFileLoggerProvider() {}

        public ILogger CreateLogger(string categoryName) {
            return new CustomFileLogger(categoryName, SharedLogger);
        }

        public void Dispose() {}
    }

    // Customized ILogger, writes logs to text files
    public class CustomFileLogger : ILogger {
        private readonly string _categoryName;
        private readonly Logger _logger;

        public CustomFileLogger(string categoryName, Logger logger) {
            _categoryName = categoryName;
            _logger = logger;
        }

        public IDisposable BeginScope<TState>(TState state) { return null; }

        public bool IsEnabled(LogLevel logLevel) {
            // Ensure that only information level and higher logs are recorded
            return logLevel >= LogLevel.Information;
        }

        public void Log<TState>(
                LogLevel logLevel,
                EventId eventId,
                TState state,
                Exception exception,
                Func<TState, Exception, string> formatter) {
            // Ensure that only information level and higher logs are recorded
            if (!IsEnabled(logLevel)) { return; }

            // Get the formatted log message
            var message = formatter(state, exception);

            _logger.LogLine($"[{logLevel}] [{_categoryName}] {message}");
        }
    }
}