using MediatR;
using MediatR.Pipeline;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Netmash.Extensions.Swagger;
using Netmash.Extensions.Swagger.Constants;
using Netmash.Security.Authentication.Tuitio;
using NetworkResurrector.Server.Application;
using Newtonsoft.Json;
using System.Reflection;

namespace NetworkResurrector.Server.Extensions
{
    public static class StartupExtensions
    {
        public static void ConfigureServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddControllers()
                .AddNewtonsoftJson(o => o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc);

            // Add basic authentication 
            services.AddTuitioAuthentication(configuration.GetSection("Tuitio")["BaseAddress"]);

            services.AddHttpContextAccessor();

            // MediatR
            services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Application.CommandHandlers.PingMachineHandler>());
            services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>));
            services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));

            // AutoMapper
            services.AddAutoMapper(
                typeof(Application.Mappings.MappingProfile).Assembly);

            // Swagger
            services.AddSwagger("NetworkResurrector Server API", AuthorizationType.Tuitio);

            // Application
            services.AddApplicationServices();

            // WakeOnLan
            services.AddWakeOnLan(configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public static void Configure(this IApplicationBuilder app)
        {
            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.ConfigureSwagger("NetworkResurrector Server API");
        }
    }
}
