using EonaCat.Logger.EonaCatCoreLogger;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;

namespace EonaCat.Logger.EonaCatCoreLogger
{
    // This file is part of the EonaCat project(s) which is released under the Apache License.
    // See the LICENSE file or go to https://EonaCat.com/License for full license details.

    public sealed class BatchingDatabaseLogger : ILogger, IDisposable
    {
        private readonly string _categoryName;
        private readonly BatchingDatabaseLoggerOptions _options;
        private readonly LoggerScopedContext _context = new();

        private readonly BlockingCollection<LogEntry> _queue;
        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
        private readonly Task _processingTask;

        private volatile bool _disposed;

        private const int MaxQueueSize = 10_000;

        public bool IncludeCorrelationId { get; }
        public event EventHandler<Exception> OnException;

        public BatchingDatabaseLogger(string categoryName, BatchingDatabaseLoggerOptions options)
        {
            _categoryName = categoryName ?? throw new ArgumentNullException(nameof(categoryName));
            _options = options ?? throw new ArgumentNullException(nameof(options));
            IncludeCorrelationId = options.IncludeCorrelationId;

            _queue = new BlockingCollection<LogEntry>(new ConcurrentQueue<LogEntry>(), MaxQueueSize);
            _processingTask = Task.Run(() => ProcessQueueAsync(_cts.Token));
        }

        public IDisposable BeginScope<TState>(TState state) => _context.BeginScope(state);

        public bool IsEnabled(LogLevel logLevel) => !_disposed && _options.IsEnabled;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (_disposed || !IsEnabled(logLevel) || formatter == null)
            {
                return;
            }

            string message = formatter(state, exception);

            string correlationId = null;
            if (IncludeCorrelationId)
            {
                correlationId = _context.Get("CorrelationId") ?? Guid.NewGuid().ToString();
                _context.Set("CorrelationId", correlationId);
            }

            var entry = new LogEntry
            {
                Timestamp = DateTime.UtcNow,
                LogLevel = logLevel.ToString(),
                Category = _categoryName,
                Message = message,
                Exception = exception?.ToString(),
                CorrelationId = correlationId
            };

            while (!_queue.TryAdd(entry))
            {
                _queue.TryTake(out _);
            }
        }

        private async Task ProcessQueueAsync(CancellationToken token)
        {
            var batch = new List<LogEntry>(_options.BatchSize);

            try
            {
                foreach (var entry in _queue.GetConsumingEnumerable(token))
                {
                    batch.Add(entry);

                    if (batch.Count >= _options.BatchSize)
                    {
                        await FlushBatchAsync(batch, token);
                    }
                }
            }
            catch (OperationCanceledException) 
            {
                // Do nothing
            }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
            finally
            {
                if (batch.Count > 0)
                {
                    await FlushBatchAsync(batch, token);
                }
            }
        }

        private async Task FlushBatchAsync(List<LogEntry> batch, CancellationToken token)
        {
            if (batch.Count == 0)
            {
                return;
            }

            try
            {
                await InsertBatchAsync(batch, token);
            }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
            finally
            {
                batch.Clear();
            }
        }

        private async Task InsertBatchAsync(List<LogEntry> batch, CancellationToken token)
        {
            using (var connection = _options.DbProviderFactory.CreateConnection())
            {
                if (connection == null)
                {
                    throw new InvalidOperationException("Failed to create database connection.");
                }

                connection.ConnectionString = _options.ConnectionString;
                await connection.OpenAsync(token);

                using (var transaction = connection.BeginTransaction())
                {
                    using (var command = connection.CreateCommand())
                    {
                        command.Transaction = transaction;
                        command.CommandText = _options.InsertCommand;

                        var timestampParam = CreateParameter(command, "Timestamp", null);
                        var logLevelParam = CreateParameter(command, "LogLevel", null);
                        var categoryParam = CreateParameter(command, "Category", null);
                        var messageParam = CreateParameter(command, "Message", null);
                        var exceptionParam = CreateParameter(command, "Exception", null);
                        var correlationParam = CreateParameter(command, "CorrelationId", null);

                        command.Parameters.Add(timestampParam);
                        command.Parameters.Add(logLevelParam);
                        command.Parameters.Add(categoryParam);
                        command.Parameters.Add(messageParam);
                        command.Parameters.Add(exceptionParam);
                        command.Parameters.Add(correlationParam);

                        foreach (var entry in batch)
                        {
                            timestampParam.Value = entry.Timestamp;
                            logLevelParam.Value = entry.LogLevel ?? (object)DBNull.Value;
                            categoryParam.Value = entry.Category ?? (object)DBNull.Value;
                            messageParam.Value = entry.Message ?? (object)DBNull.Value;
                            exceptionParam.Value = entry.Exception ?? (object)DBNull.Value;
                            correlationParam.Value = entry.CorrelationId ?? (object)DBNull.Value;

                            await command.ExecuteNonQueryAsync(token);
                        }
                    }

                    transaction.Commit();
                }
            }
        }

        private DbParameter CreateParameter(DbCommand command, string name, object value)
        {
            var param = command.CreateParameter();
            param.ParameterName = $"@{name}";
            param.Value = value ?? DBNull.Value;
            return param;
        }

        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;

            _cts.Cancel();
            _queue.CompleteAdding();

            try { _processingTask.Wait(_options.ShutdownTimeout); } catch { }

            _queue.Dispose();
            _cts.Dispose();
        }

        private sealed class LogEntry
        {
            public DateTime Timestamp { get; set; }
            public string LogLevel { get; set; }
            public string Category { get; set; }
            public string Message { get; set; }
            public string Exception { get; set; }
            public string CorrelationId { get; set; }
        }
    }
}
