using System;
using System.Linq;
using DiplomovaPrace.Web.Server.Infrastructure.Cors;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace DiplomovaPrace.Web.Server.Infrastructure.ConfigurationExtensions
{
	public static class CorsConfig
	{
		public static void AddCustomizedCors(this IServiceCollection services, IConfiguration configuration)
		{
			services.Configure<CorsOptions>(configuration.GetSection("Cors"));
			services.AddCors();
		}

		public static void UseCustomizedCors(this IApplicationBuilder app, IOptions<CorsOptions> corsOptions)
		{
			string[] allowedOrigins = corsOptions.Value.AllowedOrigins.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(item => item.Trim()).ToArray();
			app.UseCors(policy =>
			{
				policy.WithOrigins(allowedOrigins)
					.SetIsOriginAllowedToAllowWildcardSubdomains()
					.WithHeaders("Accept", "Content-Type", "Origin", "Authorization", "x-apiversion")
					.AllowCredentials()
					.AllowAnyMethod()
					.SetPreflightMaxAge(TimeSpan.FromHours(1));
			});
		}
	}
}
