using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;

namespace Kit.Helpers
{
    public static class HttpContextCore
    {
        private static IServiceProvider _serviceProvider;
        private static bool _notWebApp;

        public static void Configure(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
            _notWebApp = false;
        }

        public static void ConfigureNotWebApp()
        {
            _notWebApp = true;
        }

        public static HttpContext Current
        {
            get
            {
                if (_notWebApp)
                {
                    return null;
                }
                // var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
                object factory = _serviceProvider.GetService(typeof(IHttpContextAccessor));

                // Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
                HttpContext context = ((HttpContextAccessor)factory).HttpContext;
                // context.Response.WriteAsync("Test");

                return context;
            }
        }

        private static readonly string _contextHostUrl = "HostUrl";

        public static string GetHostUrl(this HttpContext context)
        {
            context.Items[_contextHostUrl] = context.Items[_contextHostUrl] as string ?? context.GenerateHostUrl();
            return context.Items[_contextHostUrl]!.ToString()!;
        }
        public static string GetRootUrl(this HttpContext context)
        {
            return $"{GetHostUrl(context)}{context.Request.PathBase}";
        }

        private static string GenerateHostUrl(this HttpContext context, bool checkForwardedProto = true)
        {
            HttpRequest request = context.Request;

            // Формируем RootUrl
            string scheme = request.Scheme;

            if (checkForwardedProto && request.Headers.TryGetValue("X-Forwarded-Proto", out StringValues forwardedProtoValues) && forwardedProtoValues.Count > 0)
            {
                scheme = forwardedProtoValues.First()!;
            }

            return $"{scheme}://{request.Host}";
        }
    }
}