// Copyright (c) Rodel. All rights reserved.
// <auto-generated />

using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using Markdig.Syntax;

namespace BiliCopilot.UI.Controls.Markdown.Renderers.ObjectRenderers;

internal class HtmlBlockRenderer : WinUIObjectRenderer<HtmlBlock>
{
    protected override void Write(WinUIRenderer renderer, HtmlBlock obj)
    {
        if (renderer == null)
        {
            throw new ArgumentNullException(nameof(renderer));
        }

        if (obj == null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        var stringBuilder = new StringBuilder();
        foreach (var line in obj.Lines.Lines)
        {
            var lineText = line.Slice.ToString().Trim();
            if (string.IsNullOrWhiteSpace(lineText))
            {
                continue;
            }

            stringBuilder.AppendLine(lineText);
        }

        var html = Regex.Replace(stringBuilder.ToString(), @"\t|\n|\r", string.Empty, RegexOptions.Compiled);
        html = Regex.Replace(html, @"&nbsp;", " ", RegexOptions.Compiled);
        var doc = new HtmlDocument();
        doc.LoadHtml(html);
        HtmlWriter.WriteHtml(renderer, doc.DocumentNode.ChildNodes);
    }
}
