using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using rmutr_report.Models;

namespace rmutr_report
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            var _setting = new Setting()
            {
                report_path = Configuration["Settings:ReportPath"]
                
            };
            services.AddSingleton(_setting);
            services.AddControllers();
            
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("reports", new OpenApiInfo {Title = "Reports API", Version = "v1"});
                c.SwaggerDoc("graph", new OpenApiInfo {Title = "Graph API", Version = "v1"});
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
                c.EnableAnnotations();
                // c.MapType(typeof(TimeSpan?), () => new OpenApiSchema
                // {
                //     Type = "string",
                //     Example = new OpenApiString("09:30:00")
                // });
            });

            services.AddCors(options =>
            {
                options.AddPolicy(name: "AllowAllOrigins",
                    builder =>
                    {
                        builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
                    });
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
          app.UseForwardedHeaders(new ForwardedHeadersOptions
          {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
            KnownNetworks =
            {
              new IPNetwork(IPAddress.Any, 0)
            }
          });
            app.UseSwagger(c => {
              c.RouteTemplate = "swagger/{documentName}/swagger.json";
              c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
              {
                if (!httpReq.Headers.ContainsKey("X-Forwarded-Host")) return;

                var serverUrl = $"{httpReq.Headers["X-Scheme"]}://" +
                                $"{httpReq.Headers["X-Forwarded-Host"]}" +
                                $"{httpReq.Headers["X-Forwarded-Prefix"]}";
                swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url =serverUrl}};// $"{httpReq.Scheme}://{httpReq.Host.Value}{swaggerBasePath}" } };
              });
            });

            //Swagger interface
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("reports/swagger.json", "Reports API v1");
                c.SwaggerEndpoint("graph/swagger.json", "Graph API v1");
              
                c.DefaultModelExpandDepth(0);
                c.DefaultModelsExpandDepth(-1);
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseCors("AllowAllOrigins");

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}
