using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace SelectPdf.Samples
{
    public interface IComponentHtmlRenderer
    {
        // Renders a Blazor component to a complete HTML document string,
        // wrapping the component output inside the same <html><head><body>
        // shell used by the live MainLayout. Used by CurrentWebPageToPdf to
        // capture the form (with the values entered in the page controls)
        // and convert it to PDF.
        Task<string> RenderToFullPageAsync<TComponent>(IDictionary<string, object> parameters, string baseUrl)
            where TComponent : IComponent;
    }

    public sealed class ComponentHtmlRenderer : IComponentHtmlRenderer
    {
        private readonly HtmlRenderer _htmlRenderer;

        public ComponentHtmlRenderer(HtmlRenderer htmlRenderer)
        {
            _htmlRenderer = htmlRenderer;
        }

        public Task<string> RenderToFullPageAsync<TComponent>(IDictionary<string, object> parameters, string baseUrl)
            where TComponent : IComponent
        {
            return _htmlRenderer.Dispatcher.InvokeAsync(async () =>
            {
                var paramView = ParameterView.FromDictionary(parameters);
                var output = await _htmlRenderer.RenderComponentAsync<TComponent>(paramView);
                string componentMarkup = output.ToHtmlString();

                return $@"<!DOCTYPE html>
<html lang=""en-US"">
<head>
    <meta charset=""UTF-8"">
    <base href=""{baseUrl}/"" />
    <link href=""css/tfg_style.css"" rel=""stylesheet"" type=""text/css"" media=""all"">
    <link href=""css/css.css"" rel=""stylesheet"" type=""text/css"" media=""all"">
    <link href=""css/style.css"" rel=""stylesheet"" type=""text/css"" media=""all"">
</head>
<body class=""single single-post single-format-standard custom-background custom-font-enabled single-author"">
    <div class=""hfeed site"" id=""page"">
        <div class=""wrapper"" id=""main"">
            <div class=""site-content"" id=""primary"">
                <div id=""content"" role=""main"">
                    {componentMarkup}
                </div>
            </div>
        </div>
    </div>
</body>
</html>";
            });
        }
    }
}
