using System.Text;
namespace RhythmBase.Components.RichText
{
///
/// Represents a line of dialogue, which consists of multiple dialogue components.
///
public class RDDialogueBlock
{
///
/// Gets or sets the character speaking the dialogue line.
///
public string? Character { get; set; }
///
/// Gets or sets the expression of the character.
///
public string? Expression { get; set; }
///
/// Gets or sets the content of the dialogue line.
///
///
/// The content of the dialogue line, represented as an .
///
public RDLine Content { get; set; } = "";
///
/// Serializes the dialogue line to a string.
///
/// A string representation of the dialogue line.
public string Serialize()
{
var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(Character))
{
sb.Append(Character);
if (!string.IsNullOrWhiteSpace(Expression))
{
sb.Append('_').Append(Expression);
}
sb.Append(':');
}
sb.Append(Content.Serialize());
return sb.ToString();
}
///
/// Deserializes a string into a instance.
///
/// The string to deserialize.
/// A new containing the deserialized content.
/// Thrown when the input string is null.
/// Thrown when the input string has an invalid format.
public static RDDialogueBlock Deserialize(string str)
{
str = str.Trim();
RDDialogueBlock line = new();
int mi = str.IndexOf(':');
if (mi != -1)
{
string character = str[..mi];
if (character.Contains('_'))
{
string[] parts = character.Split('_', 2);
character = parts[0];
line.Expression = parts[1];
}
line.Character = character;
}
line.Content = RDLine.Deserialize(str[(mi + 1)..]);
return line;
}
///
/// Deserializes a string into a instance, using a lookup of valid expressions.
///
/// The string to deserialize.
/// A lookup of valid expressions for each character.
/// A new containing the deserialized content.
/// Thrown when the input string is null.
/// Thrown when the input string has an invalid format.
public static RDDialogueBlock Deserialize(string str, ILookup expressions)
{
str = str.Trim();
RDDialogueBlock line = new();
int mi = str.IndexOf(':');
if (mi != -1)
{
string character = str[..mi];
string expression = "";
if (character.Contains('_'))
{
string[] parts = character.Split('_', 2);
character = parts[0];
expression = parts[1];
}
else
character = str;
if (!expressions.Contains(character))
{
line.Content = RDLine.Deserialize(str);
return line;
}
line.Character = character;
if (expressions[character].Contains(expression))
line.Expression = expression;
}
line.Content = RDLine.Deserialize(str[(mi + 1)..]);
return line;
}
///
public override string ToString() => $"{Character}({Expression}):{Content}";
}
}