using Logger.Services.Interfaces;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace Logger.Services
{
    public class LoggerServices
    {
        private readonly RequestDelegate _next;
        public LoggerServices(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context, IMonLogger _logger)
        {
            context ??= new DefaultHttpContext();

            Queue<string> queue = new Queue<string>();
            try
            {
                await _next(context);
            }
            finally
            {
                Task Tinfo = new Task(() => _logger.AddAction($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} -> {context?.Request?.Path ?? "Nothing"} -> {context?.Request?.Headers?.ToString() ?? "Nothing"} -> {context?.Request?.Host.Host ?? "Nothing"}", ref queue));
                Task Twrite = new Task(() => _logger.Write(queue));
                Tinfo.Start();
                Twrite.Start();
            }
        }
    }
}
