using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;

namespace VCommon.VSwaggerUI.VAspNetCore
{
    internal class SwaggerUiMiddleware
    {
        internal static ISwaggerUiResourceProvider ResourceProvider;
        internal static string BasePath;

        private readonly RequestDelegate _next;

        public SwaggerUiMiddleware(RequestDelegate next) => _next = next;

        public async Task Invoke(HttpContext context)
        {
            var requestPath = context.Request.Path.Value?.ToLower();

            if (requestPath?.StartsWith(BasePath) != true)
            {
                await _next.Invoke(context);
                return;
            }

            var path = requestPath.Substring(BasePath.Length);

            if (path == "/")
            {
                var qs = context.Request.QueryString.ToString();

                var html = ResourceProvider.GetIndex(qs.Length == 0 ? "api/" : qs.Substring(1));

                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync(html);
            }
            else
            {
                var fileName = Path.GetFileName(path);

                var bin = ResourceProvider.GetBinResource(fileName);
                if (null == bin)
                {
                    context.Response.StatusCode = 404;
                }
                else
                {
                    if (Path.GetExtension(fileName).ToLower() == ".css")
                        context.Response.ContentType = "text/css";
                    await context.Response.Body.WriteAsync(bin);
                }
            }
        }
    }
}
