using Autofac;
using PlanTempus.Components.Outbox;
using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.Configurations;
using PlanTempus.Core.Email;
using PlanTempus.Core.ModuleRegistry;
using PlanTempus.Core.Outbox;

namespace PlanTempus.Application
{
    public class Startup
    {
        public Startup(IWebHostEnvironment env)
        {
            var builder = new Core.Configurations.ConfigurationBuilder()
                .AddJsonFile("appconfiguration.json", optional: true, reloadOnChange: true);

            ConfigurationRoot = builder.Build();
        }

        public Core.Configurations.IConfigurationRoot ConfigurationRoot { get; private set; }

        public ILifetimeScope AutofacContainer { get; private set; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddOptions();
            services.AddRazorPages();
            //services.AddApplicationInsightsTelemetry(ConfigurationRoot["ApplicationInsights:InstrumentationKey"]);
            services.AddAntiforgery(x => x.HeaderName = "X-ANTI-FORGERY-TOKEN");

            services.Configure<Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new Common.ComponentsViewLocationExpander());
            });

        }
        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule
            {
                ConnectionString = ConfigurationRoot.GetConnectionString("DefaultConnection")
            });

            builder.RegisterModule(new TelemetryModule
            {
                TelemetryConfig = ConfigurationRoot.GetSection("ApplicationInsights").ToObject<TelemetryConfig>()
            });

            builder.RegisterModule<OutboxModule>();
            builder.RegisterModule<OutboxListenerModule>();
            builder.RegisterModule(new EmailModule
            {
                PostmarkConfiguration = ConfigurationRoot.GetSection("Postmark").ToObject<PostmarkConfiguration>()
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseRouting();

            app.UseStaticFiles();
            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapHub<MotionHub>("/motionhub");
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });

        }
    }
}
