using System;
using System.Diagnostics;
using System.Threading.Tasks;
using log4net;
using Microsoft.Owin;

namespace Control.Middleware
{
    class LoggingMiddleware : OwinMiddleware
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(LoggingMiddleware));
        public LoggingMiddleware(OwinMiddleware next) : base(next) {}
        public override async Task Invoke(IOwinContext context) {
            try {
                Stopwatch sw = Stopwatch.StartNew();
                await Next.Invoke(context);
                sw.Stop();
                log.Info("Request from: "+context.Request.RemoteIpAddress+" took "+sw.Elapsed.TotalSeconds+" seconds.");
            }
            catch (Exception e) {
                log.Error($"An exception has occurred: {e.Message} " +
                          $"|StackTrace: {e.StackTrace}");
            };
            log.Debug($"Returning: {context.Response.StatusCode}" +
                      $" to: {context.Request.RemoteIpAddress} " +
                      $"|Method: {context.Request.Method} " +
                      $"|Uri: {context.Request.Uri.Authority + context.Request.Uri.AbsolutePath} " +
                      $"|Query: {context.Request.Uri.Query}");
        }
    }
}
