using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using NLog;
using NLog.Config;
using ProfitGroup.Rdnl.Extensions;
using ProfitGroup.SampleService.Models;
using Unity;

namespace ProfitGroup.SampleService.Core.Middlewares
{
    public class SampleMiddleware : IHttpModule
    {
        private readonly SampleCreateState _sampleCreateState;

        private static NLog.ILogger Logger
        {
            get
            {
                var loggerConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nlog.config");
                LogManager.Setup().LoadConfigurationFromFile(loggerConfig);
                LogManager.Configuration = new XmlLoggingConfiguration(loggerConfig);

                return LogManager.GetCurrentClassLogger();
            }
        }

        public SampleMiddleware()
        {
            _sampleCreateState = UnityConfig.Container?.Resolve<SampleCreateState>();
        }

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += OnAuthenticateRequest;


        }

        private void OnAuthenticateRequest(object sender, EventArgs e)
        {
            var context = ((HttpApplication)sender).Context;

            if (_sampleCreateState != null && _sampleCreateState.IsProcessing)
            {
                var message = "Был получен запрос, во время создания другой пробы. Запрос был отменен.";
                Logger.Error(message);
                context.Response.Output.Write(message);
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.End();
            }
        }
    }
}