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

namespace Kit.Helpers.Mvc.TagHelpers
{
    [HtmlTargetElement("link", Attributes = "asp-context", TagStructure = TagStructure.WithoutEndTag)]
    [HtmlTargetElement("link", Attributes = "asp-prepend-domain", TagStructure = TagStructure.WithoutEndTag)]
    public class LinkTagHelper : Microsoft.AspNetCore.Mvc.TagHelpers.LinkTagHelper
    {
        public LinkTagHelper(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; }

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

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

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

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