98 lines
2.9 KiB
C#
98 lines
2.9 KiB
C#
// SzfFieldWriter.cs
|
|
|
|
using System.Text;
|
|
|
|
namespace SessionZero.Data;
|
|
|
|
/// <summary>
|
|
/// Helper class to write fields to a StringBuilder following SZF format,
|
|
/// respecting generator options like indentation.
|
|
/// </summary>
|
|
public class SzfFieldWriter
|
|
{
|
|
public readonly StringBuilder Builder;
|
|
public readonly SzfGeneratorOptions Options;
|
|
|
|
public SzfFieldWriter(StringBuilder builder, SzfGeneratorOptions options)
|
|
{
|
|
Builder = builder;
|
|
Options = options;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Writes a generic field with a string type.
|
|
/// </summary>
|
|
public void WriteField(string name, string type, object? value)
|
|
{
|
|
if (!Options.IncludeEmptyFields && (value == null || string.IsNullOrEmpty(value.ToString())))
|
|
{
|
|
return; // Skip empty fields if option is set
|
|
}
|
|
|
|
var formattedValue = FormatFieldValue(value, type);
|
|
|
|
if (Options.IndentFields)
|
|
{
|
|
Builder.AppendLine($"{Options.Indent}{name} ({type}) = {formattedValue}");
|
|
}
|
|
else
|
|
{
|
|
Builder.AppendLine($"{name} ({type}) = {formattedValue}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Writes a field with a DatasetFieldType.
|
|
/// </summary>
|
|
public void WriteField(string name, DatasetFieldType type, object? value)
|
|
{
|
|
var typeString = type switch
|
|
{
|
|
DatasetFieldType.Text => "text",
|
|
DatasetFieldType.TextField => "text-field",
|
|
DatasetFieldType.Number => "number",
|
|
DatasetFieldType.Boolean => "bool",
|
|
DatasetFieldType.Group => "group",
|
|
DatasetFieldType.Calculated => "calculated",
|
|
DatasetFieldType.System => "system",
|
|
DatasetFieldType.DatasetReference => "dataset-reference",
|
|
DatasetFieldType.DatasetType => "dataset-type",
|
|
DatasetFieldType.DatasetReferenceMultiple => "dataset-reference-multiple",
|
|
DatasetFieldType.DatasetTypeMultiple => "dataset-type-multiple",
|
|
_ => "text" // Default or unknown types
|
|
};
|
|
WriteField(name, typeString, value);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Formats field values based on their declared type for SZF output.
|
|
/// </summary>
|
|
private string FormatFieldValue(object? value, string fieldType)
|
|
{
|
|
if (value == null)
|
|
return string.Empty;
|
|
|
|
return fieldType.ToLower() switch
|
|
{
|
|
"bool" => (bool)value ? "true" : "false",
|
|
"number" => value.ToString() ?? "0",
|
|
_ => value.ToString() ?? string.Empty
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Appends a new line to the string builder.
|
|
/// </summary>
|
|
public void AppendLine()
|
|
{
|
|
Builder.AppendLine();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Appends a section header to the string builder.
|
|
/// </summary>
|
|
public void AppendSectionHeader(string header)
|
|
{
|
|
Builder.AppendLine($"[{header}]");
|
|
}
|
|
} |