using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace BulkArchiveMailer.Core
{
///
/// Minimal placeholder substitution for Subject/BodyHtml templates.
/// Deliberately simple (no conditionals/loops) - templates are short,
/// hand-edited strings, not a general templating language.
///
public static class TemplateEngine
{
private static readonly Regex PlaceholderPattern = new Regex(@"\{(?[A-Za-z0-9_]+)\}", RegexOptions.Compiled);
///
/// Replaces every "{Name}" placeholder with the matching value from
/// (case-insensitive lookup). Unknown
/// placeholders are left untouched rather than throwing, so a typo
/// in a hand-edited template shows up visibly in the preview
/// instead of crashing the scan.
///
public static string Render(string template, IDictionary values)
{
if (string.IsNullOrEmpty(template))
{
return template ?? string.Empty;
}
return PlaceholderPattern.Replace(template, match =>
{
var name = match.Groups["name"].Value;
foreach (var kvp in values)
{
if (string.Equals(kvp.Key, name, StringComparison.OrdinalIgnoreCase))
{
return kvp.Value ?? string.Empty;
}
}
return match.Value; // leave "{Unknown}" as-is
});
}
/// Renders both Subject and BodyHtml of a template for one recipient.
public static MailTemplate Render(MailTemplate template, string login, string email)
{
var values = new Dictionary(StringComparer.OrdinalIgnoreCase)
{
["Login"] = login ?? "",
["Email"] = email ?? "",
["Date"] = DateTime.Now.ToString("dd.MM.yyyy"),
};
return new MailTemplate
{
Subject = Render(template?.Subject ?? "", values),
BodyHtml = Render(template?.BodyHtml ?? "", values),
};
}
}
}