using System.Text;
using Hotline.Application.ExportWord;
using Hotline.Pdf;
using Hotline.Share.Enums.Article;
using XF.Domain.Exceptions;

namespace Hotline.Application.Tools;
public static class StringExtensions
{
    public static Stream HtmlToWord(this string value)
    {
        return WordHelper.ConvertHtmlToWord(value);
    }

    public static Stream HtmlToPDF(this string value)
    {
        return WordHelper.ConvertHtmlToPdf(value);
    }

    public static Stream HtmlToPDF(this string value, string? title, IPdfManager? pdfManager)
    {
        if (pdfManager is null)
            throw new UserFriendlyException($"非法参数: {nameof(pdfManager)}");
        var content = value
                .Replace("&nbsp;", " ")
                .Replace("&amp;", "&")
                .Replace("&quot;", "\"")
                .Replace("&gt;", ">")
                .Replace("&lt;", "<")
            ;

        //去除html标签
        var sb = new StringBuilder();
        while (!string.IsNullOrEmpty(content) && (content.StartsWith('<') || content.EndsWith('>')))
        {
            var indexright = content.IndexOf('>');
            var indexSecLeft = content.IndexOf('<', indexright);
            if (indexSecLeft < indexright)
            {
                content = content.Remove(0, indexright + 1);
            }
            else
            {
                var startIndex = indexright + 1;
                var str = content.Substring(startIndex, indexSecLeft - startIndex);
                if (!string.IsNullOrEmpty(str)) sb.AppendLine(str);
                content = content.Remove(0, indexSecLeft);
            }
        }

        var sbStr = sb.ToString();
        if (!string.IsNullOrEmpty(sbStr))
            content = sbStr;

        var stream = new MemoryStream();
        pdfManager.GeneratePdf(title, content, stream);
        stream.Seek(0, SeekOrigin.Begin);
        return stream;
    }

    public static Stream HtmlToStream(this string value, EFileType fileType, string? title = null, IPdfManager? pdfManager = null)
    {
        //if (fileType == EFileType.pdf) return value.HtmlToPDF();
        if (fileType == EFileType.pdf) return value.HtmlToPDF(title, pdfManager);
        if (fileType == EFileType.word) return value.HtmlToWord();
        throw new NotImplementedException($"无效的 fileType 入参: {fileType}");
    }
}
