using EDAViewer.HostedService;
using EDAViewer.Models;
using EDAViewer.Singleton;
using Helper.Log;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Shared;
using System;
using System.IO;
using System.Net;
using System.Reflection;

namespace EDAViewer
{

    public class Startup
    {

        private Background _Background;
        private AppSettings _AppSettings;
        private readonly IsEnvironment _IsEnvironment;
        private readonly IConfiguration _Configuration;
        private readonly IWebHostEnvironment _WebHostEnvironment;

        public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
        {
            _Configuration = configuration;
            _WebHostEnvironment = webHostEnvironment;
            _IsEnvironment = new IsEnvironment(webHostEnvironment.IsDevelopment(), webHostEnvironment.IsStaging(), webHostEnvironment.IsProduction());
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            LogLevel defaultLogLevel;
            LogLevel log4netLogLevel;
            IConfigurationSection configurationSection;
            configurationSection = _Configuration.GetSection("Logging:LogLevel:Default");
            if (configurationSection is null || configurationSection.Value is null)
                defaultLogLevel = LogLevel.Debug;
            else if (!Enum.TryParse<LogLevel>(configurationSection.Value, out defaultLogLevel))
                defaultLogLevel = LogLevel.Debug;
            configurationSection = _Configuration.GetSection("Logging:LogLevel:Log4netProvider");
            if (configurationSection is null || configurationSection.Value is null)
                log4netLogLevel = defaultLogLevel;
            else if (!Enum.TryParse<LogLevel>(configurationSection.Value, out log4netLogLevel))
                log4netLogLevel = defaultLogLevel;
            _AppSettings = _Configuration.Get<AppSettings>();
            if (!_IsEnvironment.Production)
                _AppSettings.Server = _AppSettings.Server.Replace('.', '_');
            if (string.IsNullOrEmpty(_AppSettings.WorkingDirectoryName))
                throw new Exception("Working directory name must have a value!");
            Assembly assembly = Assembly.GetExecutingAssembly();
            string workingDirectory = Log.GetWorkingDirectory(assembly.GetName().Name, _AppSettings.WorkingDirectoryName);
            services.AddLogging(logging =>
            {
                logging.AddProvider(new DebugProvider(defaultLogLevel));
                logging.AddProvider(new ConsoleProvider(defaultLogLevel));
                logging.AddProvider(new Log4netProvider(typeof(Startup), log4netLogLevel, workingDirectory));
            });

            services.AddDirectoryBrowser();
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddServerSideBlazor();

            // services.AddSingleton<WebClient, WebClient>();
            // services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            _Background = new Background(_IsEnvironment, _AppSettings, workingDirectory);
            services.AddSingleton<Singleton.IBackground, Background>(b => _Background);
            services.AddSingleton<AppSettings, AppSettings>(appSettings => _AppSettings);
            services.AddSingleton<IsEnvironment, IsEnvironment>(isEnvironment => _IsEnvironment);
            services.AddHostedService(t => new TimedHostedService(_IsEnvironment, _Background, t.GetRequiredService<IServiceProvider>()));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "EDAViewer", Version = "v1" });
            });
        }

        // 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)
        {
            if (env.IsDevelopment())
            {
                if (string.IsNullOrEmpty(_AppSettings.URLs))
                {
                    Environment.ExitCode = -1;
                    lifetime.StopApplication();
                }

                app.UseDeveloperExceptionPage();

                app.UseSwagger(c =>
                {
                    c.SerializeAsV2 = true;
                });

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "EDA Viewer API V1");
                    c.RoutePrefix = string.Empty;
                });
            }
            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();

                app.UseSwagger(c =>
                {
                    c.SerializeAsV2 = true;
                });

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/EDAViewer/swagger/v1/swagger.json", "EDA Viewer API V1");
                    c.RoutePrefix = string.Empty;
                });
            }

            app.UseDirectoryBrowser(new DirectoryBrowserOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.WebRootPath, "images")),
                RequestPath = "/MyImages"
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

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

    }

}