using Azure.Core;
using HeaderRecord;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Net.Http;

namespace EVCB_OCPP.Service
{
    public static partial class AppExtention
    {
        public static void AddHeaderRecordService(this IServiceCollection services)
        {
            services.AddTransient<HeaderRecordService>();
        }

        public static void UseHeaderRecordService(this WebApplication webApplication)
        {
            webApplication.Use(async (context, next) =>
            {
                var servcie = context.RequestServices.GetService<HeaderRecordService>();
                servcie.LogRequest(context.TraceIdentifier, context.Request);
                await next(context);
                servcie.LogResponse(context.TraceIdentifier, context.Response);
                return;
            });
        }
    }
}

namespace HeaderRecord
{

    public class HeaderRecordService
    {
        private readonly ILogger<HeaderRecordService> logger;

        public HeaderRecordService(ILogger<HeaderRecordService> logger)
        {
            this.logger = logger;
        }

        internal void LogRequest(string traceIdentifier, HttpRequest request)
        {
            logger.LogInformation("LogRequest============================================================");
            logger.LogInformation("{id} {method} {path} {protocol}", traceIdentifier, request.Method, request.Path, request.Protocol);
            foreach (var headerKey in request.Headers.Keys)
            {
                logger.LogInformation("{id} {key} {value}", traceIdentifier, headerKey, request.Headers[headerKey]);
            }
            logger.LogInformation("LogRequest============================================================");
        }

        internal void LogResponse(string traceIdentifier, HttpResponse response)
        {
            logger.LogInformation("LogResponse============================================================");
            foreach (var headerKey in response.Headers.Keys)
            {
                logger.LogInformation("{id} {key} {value}", traceIdentifier, headerKey, response.Headers[headerKey]);
            }
            logger.LogInformation("LogResponse============================================================");
        }
    }
}
