using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Text.Encodings.Web;

namespace Kit.Helpers.Mvc.TagHelpers
{
    //public class ScriptIdCollection : List<string>
    //{

    //}
    [HtmlTargetElement("script", Attributes = "asp-context")]
    [HtmlTargetElement("script", Attributes = "asp-prepend-domain")]
    [HtmlTargetElement("script", Attributes = "asp-await-collection")]
    public class ScriptTagHelper : Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper
    {
        public ScriptTagHelper(IWebHostEnvironment hostingEnvironment, TagHelperMemoryCacheProvider cacheProvider, IFileVersionProvider fileVersionProvider, HtmlEncoder htmlEncoder, JavaScriptEncoder javaScriptEncoder, IUrlHelperFactory urlHelperFactory) : base(hostingEnvironment, cacheProvider, fileVersionProvider, htmlEncoder, javaScriptEncoder, urlHelperFactory)
        {
        }

        [HtmlAttributeName("asp-context")]
        public HttpContext? HttpContext { get; set; }

        [HtmlAttributeName("asp-prepend-domain")]
        public bool NeedPrependDomain { get; set; }

        //[HtmlAttributeName("asp-await-collection")]
        //public ScriptIdCollection? AwaitCollection { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);
            if (NeedPrependDomain && HttpContext != null)
            {
                string rootUrl = HttpContext.GetRootUrl();

                TagHelperAttribute attributeSrc = output.Attributes["src"];
                if (attributeSrc != null)
                {
                    var src = output.Attributes["src"].Value.ToString();

                    // Заменяем символ "~" на ваш домен
                    if (src.StartsWith("~"))
                    {
                        src = rootUrl + src.Substring(1);
                    }
                    else if (src.StartsWith("/"))
                    {
                        src = rootUrl + src;
                    }

                    output.Attributes.SetAttribute("src", src);

                    //if (AwaitCollection != null)
                    //{
                    //    TagHelperAttribute attributeId = output.Attributes["id"];
                    //    string id = attributeId?.Value?.ToString() ?? "script".AppendToken();
                    //    output.Attributes.SetAttribute("id", id);

                    //    AwaitCollection.Add(id);
                    //}
                }
                else if (output.PostElement != null && output.PostElement.IsEmptyOrWhiteSpace == false)
                {
                    string str = output.PostElement.GetContent();
                    str = str.Replace("src=\"/", $"src=\"{rootUrl}/").Replace("src=\"~/", $"src=\"{rootUrl}/");
                    output.PostElement.SetHtmlContent(str);

                    ;
                }
            }
        }
    }
    //[HtmlTargetElement("scriptawaiter")]
    //public class ScriptAwaiterTagHelper : TagHelper
    //{
    //    public const string EventNameAllLoaded = "allScriptsLoaded";

    //    [HtmlAttributeName("asp-await-collection")]
    //    public ScriptIdCollection? AwaitCollection { get; set; }

    //    public override void Init(TagHelperContext context)
    //    {
    //        base.Init(context);
    //    }

    //    public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    //    {
    //        output.TagName = "script";
    //        output.TagMode = TagMode.StartTagAndEndTag;

    //        output.Attributes.SetAttribute("class", "scriptawaiter");

    //        var stringBuilder = new StringBuilder();

    //        stringBuilder.AppendLine("");
    //        stringBuilder.AppendLine("const awaitingScripts = " + AwaitCollection?.ToDictionary(x => x, x=> false).JsonSerialize(true) ?? "{}");
    //        stringBuilder.AppendLine("console.log(awaitingScripts);");
    //        stringBuilder.AppendLine("$('script[src]').on('load', function() {");
    //        {
    //            stringBuilder.AppendLine("var itemId = this.id;");
    //            stringBuilder.AppendLine("console.log('file loaded: ' + itemId);");
    //            stringBuilder.AppendLine("if (Object.keys(awaitingScripts).indexOf(itemId) != -1) {");
    //            stringBuilder.AppendLine("awaitingScripts[itemId] = true;");
    //            stringBuilder.AppendLine("var allLoaded = true;");
    //            stringBuilder.AppendLine("Object.keys(awaitingScripts).forEach(key => { if (awaitingScripts[key] == false) allLoaded = false; });");
    //            stringBuilder.AppendLine("if (allLoaded) { window.dispatchEvent(new Event('" + EventNameAllLoaded + "')); };");
    //            stringBuilder.AppendLine("}");
    //        }
    //        stringBuilder.AppendLine("});");

    //        output.Content.SetHtmlContent(stringBuilder.ToString());

    //        return Task.CompletedTask;
    //    }
    //}
}
