using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace mustache
{
///
/// Generates text by substituting an object's values for placeholders.
///
public sealed class Generator
{
private readonly IGenerator _generator;
private readonly List> _foundHandlers;
private readonly List> _notFoundHandlers;
///
/// Initializes a new instance of a Generator.
///
/// The text generator to wrap.
internal Generator(IGenerator generator)
{
_generator = generator;
_foundHandlers = new List>();
_notFoundHandlers = new List>();
}
///
/// Occurs when a key/property is found.
///
public event EventHandler KeyFound
{
add { _foundHandlers.Add(value); }
remove { _foundHandlers.Remove(value); }
}
///
/// Occurs when a key/property is not found in the object graph.
///
public event EventHandler KeyNotFound
{
add { _notFoundHandlers.Add(value); }
remove { _notFoundHandlers.Remove(value); }
}
///
/// Gets the text that is generated for the given object.
///
/// The object to generate the text with.
/// The text generated for the given object.
public string Render(object source)
{
return render(CultureInfo.CurrentCulture, source);
}
///
/// Gets the text that is generated for the given object.
///
/// The format provider to use.
/// The object to generate the text with.
/// The text generated for the given object.
public string Render(IFormatProvider provider, object source)
{
if (provider == null)
{
provider = CultureInfo.CurrentCulture;
}
return render(provider, source);
}
private string render(IFormatProvider provider, object source)
{
KeyScope scope = new KeyScope(source);
foreach (EventHandler handler in _foundHandlers)
{
scope.KeyFound += handler;
}
foreach (EventHandler handler in _notFoundHandlers)
{
scope.KeyNotFound += handler;
}
StringWriter writer = new StringWriter(provider);
_generator.GetText(scope, writer);
return writer.ToString();
}
}
}