using AipGateway.API.Application.UtilityServices;
using AipGateway.API.Domain.Common.Utilities;
using AipGateway.API.Domain.Entities;
using AipGateway.API.Domain.IRepositories.IGenericRepositories;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace AipGateway.API.Application.Pipeline.Middlewares.Logging
{
    public class LoggingDbProcess
    {
        private readonly ILogger<LoggingDbProcess> _log;

        private readonly BlockingConcurrentQueue<LoggingDb> _logQueue;
        private readonly CancellationTokenSource _cancellationTokenSource;

        public LoggingDbProcess(ILogger<LoggingDbProcess> logger)
        {
            _log = logger;
            _logQueue = new BlockingConcurrentQueue<LoggingDb>();
            _cancellationTokenSource = new CancellationTokenSource();

            _log.LogError("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");
            // Start a separate thread to process logs
            Task.Run(ProcessLogsAsync);
        }

        public void EnqueueLog(LoggingDb log)
        {
            _logQueue.Enqueue(log);
        }

        private async Task ProcessLogsAsync()
        {
            while (!_cancellationTokenSource.Token.IsCancellationRequested)
            {
                if (_logQueue.TryDequeue(out var log))
                {
                    // Save log to the database
                    await SaveLogToDatabaseAsync(log);
                }
                else
                {
                    // Sleep or wait for new logs
                    await Task.Delay(100);
                }
            }
        }

        private async Task SaveLogToDatabaseAsync(LoggingDb log)
        {
            IUnitOfWork? unitOfWork = ServiceContainer.provider.GetService<IUnitOfWork>();
            if (unitOfWork != null)
            {
                if (log.logType == 1)
                {
                    TbAipApiCallLog? aipCallLog = log.logData as TbAipApiCallLog;
                    if (aipCallLog != null)
                    {
                        unitOfWork.AipApiCallLogRepository.AddAsync(aipCallLog);
                        unitOfWork.Complete();
                        _log.LogError("Save Log...");
                    }
                    else
                    {
                        _log.LogError("eeeeeeeeeeeeeeeeeeeeeeeee");
                    }
                }
                else
                {
                    _log.LogError("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: {0}", log.logType);
                }
            }
            else
            {
                _log.LogError("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
            }
        }

        public void StopProcessing()
        {
            _cancellationTokenSource.Cancel();
        }
    }
}
