using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System;
using System.IO;
using System.Reflection.PortableExecutable;
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace EVCB_OCPP.WEBAPI.Middleware
{
    public sealed class BodyRewindMiddleware
    {
        private readonly RequestDelegate _next;

        public BodyRewindMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            string body = await new StreamReader(context.Request.Body).ReadToEndAsync();
            context.Items.Add("PreloadBody", body);
            context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
            await _next(context);

            //using (var injectedRequestStream = new MemoryStream())
            //{
            //    var bytesToWrite = System.Text.Encoding.UTF8.GetBytes(body);
            //    injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
            //    injectedRequestStream.Seek(0, SeekOrigin.Begin);
            //    context.Request.Body = injectedRequestStream;
            //    await _next(context);
            //}
        }
    }
}

public static class BodyRewindExtensions
{
    public static IApplicationBuilder EnableRequestBodyRewind(this IApplicationBuilder app)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }

        return app.UseMiddleware<EVCB_OCPP.WEBAPI.Middleware.BodyRewindMiddleware>();
    }

    public static string GetPreLoadBody(this HttpContext httpContext)
    {
        return httpContext.Items["PreloadBody"] as string;
    }
}
