using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Quadarax.Foundation.Core.Value
{
///
/// Represents a string with parameters (bracked by defined tags) that can be replaced.
/// Sample: Hello {name}, how are you?
/// If name = John, the result will be: Hello John, how are you?
///
public class ParameterizedString
{
private readonly string _parameterPrefix;
private readonly string _parameterPostfix;
private readonly string _initialString;
private readonly IDictionary _parameters;
public string[] Parameters => _parameters.Keys.ToArray();
///
/// Creates a new instance of the ParameterizedString class.
///
/// Initial string with parameters thats bracked by and
/// Left parameter name bracket
/// Right parameter name bracket
public ParameterizedString(string initialString,string parameterPrefix = "", string parameterPostfix = "")
{
_parameterPostfix = parameterPostfix;
_parameterPrefix = parameterPrefix;
_initialString = initialString;
_parameters = new Dictionary();
}
///
/// Add new parameter with value.
///
/// Parameter name.
/// Parameter value
/// If parameter already exists, returns false
public bool AddParameter(string name, string value)
{
if(_parameters.ContainsKey(name))
{
return false;
}
_parameters.Add(name, value);
return true;
}
///
/// Set existing parameter value.
///
/// Parameter name.
/// Parameter value
/// If parameter not exists, returns false
public bool SetParameter(string name, string value)
{
if(!_parameters.ContainsKey(name))
{
return false;
}
_parameters[name] = value;
return true;
}
///
/// Add or Set existing parameter value.
///
/// Parameter name.
/// Parameter value
public void AddOrSetParameter(string name, string value)
{
if(!SetParameter(name, value))
AddParameter(name, value);
}
///
/// Renders the string with the parameters.
///
/// Transalted string
public override string ToString()
{
var sb = new StringBuilder(_initialString);
foreach (var key in _parameters.Keys)
{
sb.Replace(_parameterPrefix + key + _parameterPostfix, _parameters[key]);
}
return sb.ToString();
}
}
}