using Microsoft.EntityFrameworkCore;
using OliverBooth.Data;
using OliverBooth.Data.Web;
using OliverBooth.Markdown;
using SmartFormat;
using SmartFormat.Extensions;
namespace OliverBooth.Services;
///
/// Represents a service that renders MediaWiki-style templates.
///
public sealed class TemplateService
{
private readonly IDbContextFactory _webContextFactory;
private readonly SmartFormatter _formatter;
///
/// Initializes a new instance of the class.
///
/// The factory.
public TemplateService(IDbContextFactory webContextFactory)
{
_formatter = Smart.CreateDefaultSmartFormat();
_formatter.AddExtensions(new DefaultSource());
_formatter.AddExtensions(new ReflectionSource());
_formatter.AddExtensions(new DateFormatter());
_webContextFactory = webContextFactory;
Current = this;
}
public static TemplateService Current { get; private set; } = null!;
///
/// Renders the specified template with the specified arguments.
///
/// The template to render.
/// The rendered template.
///
/// is .
///
public string RenderTemplate(TemplateInline templateInline)
{
if (templateInline is null) throw new ArgumentNullException(nameof(templateInline));
using WebContext webContext = _webContextFactory.CreateDbContext();
ArticleTemplate? template = webContext.ArticleTemplates.Find(templateInline.Name);
if (template is null)
{
return $"{{{{{templateInline.Name}}}}}";
}
var formatted = new
{
templateInline.ArgumentList,
templateInline.ArgumentString,
templateInline.Params,
};
try
{
return Markdig.Markdown.ToHtml(_formatter.Format(template.FormatString, formatted));
}
catch
{
return $"{{{{{templateInline.Name}|{templateInline.ArgumentString}}}}}";
}
}
}