using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Identity;
using DotVVM.Framework.Hosting;
using ElectroShop.Services;
using ElectroShop.DAL;
using ElectroShop.DAL.Entities;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System;

namespace ElectroShop
{
    public class Startup
    {
        public IConfiguration Configuration { get; private set; }
        private IApplicationBuilder _app;
        public static string pathToTempFiles = "App_Data/Temp";
        public static string projectRootFolder = "";

        public static string absoluteURI = "";
        public Startup(IHostingEnvironment env)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json");

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDataProtection();
            services.AddAuthorization();
            services.AddWebEncoders();
            services.AddTransient(typeof(UserService));
            services.AddTransient(typeof(CathegoryService));
            services.AddTransient(typeof(ElectronicComponentService));
            services.AddEntityFrameworkSqlServer()
                .AddDbContext<ElectroShopDBContext>(options =>
                {
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
                });
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ElectroShopDBContext>()
                .AddDefaultTokenProviders();
            services.ConfigureApplicationCookie(o => { o.LoginPath = new PathString("/Authentication/SignIn"); });
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = "/Authentication/SignIn";
                });
            services.AddDotVVM(options =>
            {
                options.AddDefaultTempStorages("Temp");
                options.AddReturnedFileStorage("Temp");
            });
            // ASP.NET Core
            services.AddDotVVM(o => o.AddUploadedFileStorage(pathToTempFiles));

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            _app = app;
            loggerFactory.AddConsole();

            //_app.Use(async (httpContext, next) =>
            //{
            //    CallContext.LogicalSetData("CurrentContextKey", httpContext);
            //    try
            //    {
            //        await next();
            //    }
            //    finally
            //    {
            //        CallContext.FreeNamedDataSlot("CurrentContextKey");
            //    }
            //});
            projectRootFolder = env.ContentRootPath;

            _app.UseAuthentication();
            // use DotVVM
            var dotvvmConfiguration = _app.UseDotVVM<DotvvmStartup>(env.ContentRootPath);

            // use static files
            _app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(env.WebRootPath)
            });

            IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
            IServiceScope scope = scopeFactory.CreateScope();

            scope.ServiceProvider.GetService<ElectroShopDBContext>()
                 .Database.Migrate();

            var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var dbContext = scope.ServiceProvider.GetRequiredService<ElectroShopDBContext>();
            var dbInitializer = new DbInitializer(dbContext, userManager, roleManager);
            dbInitializer.Initialize();

        }

        public const string AuthenticationScheme = "Cookie";
    }
}
