using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace Kit.Helpers.Mvc.TagHelpers
{
    [HtmlTargetElement(Attributes = "asp-viewmodel", TagStructure = TagStructure.NormalOrSelfClosing)]
    public class BootstrapTagHelper : TagHelper
    {
        [HtmlAttributeName("asp-viewmodel")]
        public BaseViewModel Model { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);
            if (Model == null || Model.NeedLoadBootstrap || output.Attributes.IsNullOrEmpty())
            {
                return;
            }

            IEnumerable<KeyValuePair<string, string>> keyValuePairs = output.Attributes!.Select(x => new KeyValuePair<string, string>(x.Name, x.Value?.ToString() ?? string.Empty));
            var keyValuePairsNew = new List<KeyValuePair<string, string>>();
            keyValuePairs.ForEach(x =>
            {
                string key = x.Key;
                string value = x.Value?.ToString() ?? string.Empty;

                if (x.Key.ToLowerEquals("class"))
                {
                    value = ProcessClassAttributeValue(value);
                }
                else if (x.Key.ToLowerStartsWith("data-bs-"))
                {
                    key = ProcessDataBsAttributeName(x.Key);
                }

                keyValuePairsNew.Add(new KeyValuePair<string, string>(key, value));
            });

            output.Attributes.Clear();
            keyValuePairsNew.ForEach(x => output.Attributes.SetAttribute(x.Key, x.Value));
        }

        private string ProcessClassAttributeValue(string value)
        {
            return (value ?? string.Empty).Split(' ').ToList().Select(x =>
            {
                if (Model.NeedDowngradeBootstrap)
                {
                    if (x.StartsWith("ms-")) return "ml-" + x.Substring(3);
                    if (x.StartsWith("me-")) return "mr-" + x.Substring(3);
                    if (x.StartsWith("ps-")) return "pl-" + x.Substring(3);
                    if (x.StartsWith("pe-")) return "pr-" + x.Substring(3);
                }

                if (Model.NeedDowngradeFaIcons)
                {
                    if (x.ToLowerEquals("fa-solid")) return "fa";
                }

                return x;
            }).Join(" ");
        }
        private string ProcessDataBsAttributeName(string value)
        {
            return "data-" + value.Substring("data-bs-".Length);
        }
    }
}
