using System;
using System.IO.Abstractions;
using System.Security.Principal;
using BO.AppServer.Business.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using BO.AppServer.Data.Entity;
using BO.AppServer.Data.Repository;
using BO.AppServer.Metadata.Configuration;
using BO.AppServer.Web.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Quadarax.Foundation.Core.Data.Domain;
using Quadarax.Foundation.Core.Data.Interface.Domain;

namespace AppServer
{
    public class Startup
    {
        private ConfigurationService _srvConfiguration;
        private IWebHostEnvironment _env;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            //    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            // EF enable
            services.AddDbContext<BOContext>();
            services.AddDbContext<IFDbContext>();

            // Identity framework enable
            services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<IFDbContext>()
            .AddDefaultTokenProviders();

            //Use file abstractions
            services.AddSingleton<IFileSystem,FileSystem>();

            // Inject IPrincipal to get current user in all levels
            services.AddHttpContextAccessor();
            services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext?.User);

            // Bo Services
            var cfg = new Configuration();
            Configuration.GetSection("Bo").Bind(cfg);
            services.Configure<Configuration>(Configuration.GetSection("Bo"));
            services.AddScoped<AccessService>();
            services.AddSingleton<ConfigurationService>();
            services.AddScoped<UserService>();
            services.AddScoped<StatisticsService>();
            services.AddScoped<CatalogueService>();
            services.AddScoped<WorkspaceService>();
            services.AddScoped<StorageService>();
            services.AddScoped<DocumentService>();

            // Bo Repos
            services.AddScoped<DataDomain, BOContext>();
            services.AddScoped<IDomainContextResolver<DataDomain>, DomainContextResolver<DataDomain>>();
            services.AddScoped<IUnitOfWork<DataDomain>, UnitOfWorkDataDomain>();
            services.AddScoped<UserRepo>();
            services.AddScoped<WorkspaceRepo>();
            services.AddScoped<WorkspaceBillingRepo>();
            services.AddScoped<StructureRepo>();
            services.AddScoped<BillingPlanRepo>();
            services.AddScoped<MimeTypeRepo>();
            services.AddScoped<StatisticRepo>();
            services.AddScoped<WorkspaceRepo>();
            services.AddScoped<MetadocumentRepo>();
            services.AddScoped<ArtifactRepo>();


            // Session framework
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.Parse(cfg.System.SessionIdleTimeout);
            });


            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, IServiceProvider service)
        {
            _env = env;

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/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();
            }

            //May create IF database structure
            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<IFDbContext>();
                context.Database.EnsureCreated();
            }

            _srvConfiguration = (ConfigurationService)service.GetService(typeof(ConfigurationService));
            lifetime.ApplicationStarted.Register(OnApplicationStarted);

            if (_srvConfiguration.Configuration.System.UseSSL)
                app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            // Security support
            app.UseAuthentication();
            app.UseAuthorization();

            // Session support
            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }

        private void OnApplicationStarted()
        {
            _srvConfiguration.Install();
            if (_env.IsDevelopment())
            {
                _srvConfiguration.InstallDev();
            }
            _srvConfiguration.LogInfo("Application server is fully initialized.");
        }
    }
}
