// ***********************************************************************
// 
//     Heath
// 
// ***********************************************************************
using Lib.Common.LoggingAPI.Common.Settings;
using Microsoft.AspNetCore.Http;
using Microsoft.IO;
using Serilog;
namespace Lib.Common.LoggingAPI.Service.Middleware.HttpLogger
{
    /// 
    /// Handles HTTP logging.
    /// 
    public class HttpLoggingMiddleware
    {
        private readonly ILogger logger;
        private readonly RequestDelegate requestProcess;
        private readonly ServiceSettings settings;
        private readonly RecyclableMemoryStreamManager recyclableMemoryStreamManager;
        /// 
        /// Creates a new instrance of .
        /// 
        /// The request delegate process.
        /// The logger representig an instance of .
        /// The service settings.
        public HttpLoggingMiddleware(RequestDelegate requestProcess, ILogger logger, ServiceSettings settings)
        {
            this.logger = logger;
            this.requestProcess = requestProcess;
            this.settings = settings;
            recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
        }
        /// 
        /// Invoke method.
        /// 
        /// The HTTP context.
        /// 
        public async Task Invoke(HttpContext context)
        {
            await LogRequest(context);
            await LogResponse(context);
        }
        /// 
        /// Logs an incoming HTTP request.
        /// 
        /// The HTTP context.
        /// A  representing the asynchronous operation.
        private async Task LogRequest(HttpContext context)
        {
            await this.logger.LogRequest(context, this.recyclableMemoryStreamManager, this.settings.ServiceId);
        }
        /// 
        /// Logs an outcome HTTP response.
        /// 
        /// The HTTP context.
        /// A  representing the asynchronous operation.
        private async Task LogResponse(HttpContext context)
        {
            await this.logger.LogResponse(context, recyclableMemoryStreamManager, requestProcess, this.settings.ServiceId);
        }
    }
}