using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace MEU.API.MiddleWare
{
    public class AddErrorLogToHeaderMiddelware
    {
        private readonly RequestDelegate next;

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

        public async Task Invoke(HttpContext context )
        {
            if (ErrorHandlingMiddleware.enableDebug)
            {
                var watch = new Stopwatch();
                watch.Start();
                context.Response.OnStarting(state => {
                    var httpContext = (HttpContext)state;
                    
                    httpContext.Response.Headers.Add("X-Response-Time-Milliseconds", new Microsoft.Extensions.Primitives.StringValues(watch.ElapsedMilliseconds.ToString() + " ms"));

                    var contextData = AppHttpContext.Current;
                    string Log = "No any log";
                    if (contextData != null && contextData.Items.ContainsKey("LOG_DATA"))
                    {
                        if (contextData.Items["LOG_DATA"]!=null)
                        {
                            Log = contextData.Items["LOG_DATA"].ToString();
                            Log = Log.Replace(Environment.NewLine, "");
                        }                     
                    }
                    httpContext.Response.Headers.Add("X-Log-Data", new Microsoft.Extensions.Primitives.StringValues(Log));
                    return Task.CompletedTask;
                }, context);
            }
            await next(context);

        }

        
    }
}
