
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace api
{
    public class AppShellMiddleware
    {
        private readonly RequestDelegate _next;
        private string _filename;
        private IHostingEnvironment _hostEnv;
        private string[] _exceptUrls;

        public AppShellMiddleware(RequestDelegate next, IHostingEnvironment hostingEnvironment, AppShellMiddlewareOptions opts)
        {
            _next = next;
            _filename = opts.filename;
            _hostEnv = hostingEnvironment;
            _exceptUrls = opts.exceptUrls;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            if (!_exceptUrls.All(x => context.Request.Path.Value.Contains(x)))
            {
                await context.Response.SendFileAsync(Path.Combine(_hostEnv.WebRootPath, _filename));
            }
            else
            {
                await _next(context);
            }
        }
    }

    public class AppShellMiddlewareOptions
    {
        public AppShellMiddlewareOptions()
        {
            filename = "index.html";
        }
        public string filename { get; set; }
        public string[] exceptUrls { get; set; }
    }
    public static class AppShellMiddlewareExtensions
    {
        public static IApplicationBuilder UseAppShellEntrypoint(this IApplicationBuilder builder, AppShellMiddlewareOptions opts = null)
        {
            return builder.UseMiddleware<AppShellMiddleware>(opts ?? new AppShellMiddlewareOptions());
        }

        public static IServiceCollection AddAppShell(this IServiceCollection svc)
        {
            return svc.AddSingleton<AppShellMiddleware>();
        }
    }
}