using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace AipGateway.API.Application.Pipeline.Middlewares.Behaviours
{
    public class LoggingBehaviour
    {
        private readonly ILogger<HttpRequest> _log;
        //private readonly ICurrentUserService _currentUserService;
        private readonly RequestDelegate _next;
        public LoggingBehaviour(ILogger<HttpRequest> logger, RequestDelegate next)
        {
            _log = logger;
            //_currentUserService = currentUserService;
            _next = next;
            _log.LogError("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo: LoggingBehaviour");
        }

        public async Task InvokeAsync(HttpContext context)
        {
            //_log.LogError("LoggingBehaviour Invoke Before:");
            //var requestName = context.Request.Path;
            //var requestedPath = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path} {context.Request.QueryString}".Trim();
            //var userName = "Swagger";

            //if (!string.IsNullOrEmpty(_currentUserService.Email))
            //{
            //    userName = _currentUserService.Email;
            //}

            await _next(context);

            await Task.FromResult(Task.CompletedTask);

            _log.LogError("********************************************************************************* LoggingBehaviour: BEFORE");
            //_log.LogError("LoggingBehaviour Invoke  After:");
            //_log.LogError("API Request Invoke  After: {Name} {@RequestedPath} {@UserName}", requestName, requestedPath, userName);
            //Thread.Sleep(5000);
            _ = ProcessAdditionalWorkAsync();

            return;
        }

        private async Task ProcessAdditionalWorkAsync()
        {
            try
            {
                await Task.Delay(TimeSpan.FromSeconds(10));
                _log.LogError("********************************************************************************* LoggingBehaviour: AFTER");
            }
            catch (Exception ex)
            {
                _log.LogError("********************************************************************************* LoggingBehaviour: AFTER {0}", ex.Message);
            }
        }
    }
}

