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();

            try
            {
                _logger.AddAction($"{this.GetType().Name} -> {context?.Request?.Method} -> {context?.Request?.Path} -> {context?.Request?.Headers} -> {context?.Request?.Host}");
                await _next(context);
            }
            finally
            {
                Task Twrite = new Task(() => _logger.Write());
                Twrite.Start();
            }
        }
    }
}
