SessionZero.SzfToolkit-Dotnet/SessionZero.SzfLib/Objects/SzfObject.cs

87 lines
2.7 KiB
C#

using SessionZero.SzfLib.Parser;
namespace SessionZero.SzfLib.Objects;
public abstract class SzfObject : ISzfObject
{
public virtual string SzfType { get; set; }
public string SzfVersion { get; set; } = "1.0.0";
public List<SzfSection> Sections { get; set; } = new();
/// <summary>
/// Handles specific parsing logic for the SzfObject that overrides this method.
/// </summary>
/// <returns></returns>
public virtual ISzfObject? Parse()
{
return this;
}
/// <summary>
/// Gets the value of a field in the Metadata section.
/// </summary>
/// <param name="fieldName"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public string GetMetadataField(string fieldName)
{
if (string.IsNullOrEmpty(fieldName))
{
throw new ArgumentException("Field name cannot be null or empty.", nameof(fieldName));
}
return GetFieldValue("Metadata", fieldName);
}
/// <summary>
/// Gets the value of a field in a specific section. Can handle nested sections using dot notation (e.g., "Section.Subsection").
/// </summary>
/// <param name="sectionName"></param>
/// <param name="fieldName"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public string GetFieldValue(string sectionName, string fieldName)
{
if (string.IsNullOrEmpty(sectionName))
{
throw new ArgumentException("Section name cannot be null or empty.", nameof(sectionName));
}
if (string.IsNullOrEmpty(fieldName))
{
throw new ArgumentException("Field name cannot be null or empty.", nameof(fieldName));
}
var sectionPath = sectionName.Split('.');
foreach (var section in Sections)
{
var result = FindFieldValueInSection(section, sectionPath, 0, fieldName);
if (result != string.Empty) return result;
}
return string.Empty;
}
public string FindFieldValueInSection(SzfSection section, string[] path, int depth, string fieldName)
{
if (section.Name != path[depth]) return string.Empty;
if (depth == path.Length - 1)
{
if (section.Fields.TryGetValue(fieldName, out var field) && field is SzfField szfField) return szfField.Value ?? string.Empty;
return string.Empty;
}
foreach (var subsection in section.Subsections.Values)
{
var result = FindFieldValueInSection(subsection, path, depth + 1, fieldName);
if (result != string.Empty) return result;
}
return string.Empty;
}
}