using System.Collections.Generic; namespace SabreTools.Data.Models.Metadata { /// /// Specialized dictionary base for item types /// public abstract class DictionaryBase : Dictionary { /// /// Read a key as the specified type, returning null on error /// public T? Read(string key) { try { if (!ValidateKey(key)) return default; if (this[key] is not T) return default; return (T?)this[key]; } catch { return default; } } /// /// Read a key as a bool, returning null on error /// public bool? ReadBool(string key) { if (!ValidateKey(key)) return null; bool? asBool = Read(key); if (asBool is not null) return asBool; string? asString = Read(key); return asString?.ToLowerInvariant() switch { "true" or "yes" => true, "false" or "no" => false, _ => null, }; } /// /// Read a key as a double, returning null on error /// public double? ReadDouble(string key) { if (!ValidateKey(key)) return null; double? asDouble = Read(key); if (asDouble is not null) return asDouble; string? asString = Read(key); if (asString is not null && double.TryParse(asString, out double asStringDouble)) return asStringDouble; return null; } /// /// Read a key as a long, returning null on error /// /// TODO: Add logic to convert SI suffixes and hex public long? ReadLong(string key) { if (!ValidateKey(key)) return null; long? asLong = Read(key); if (asLong is not null) return asLong; string? asString = Read(key); if (asString is not null && long.TryParse(asString, out long asStringLong)) return asStringLong; return null; } /// /// Read a key as a string, returning null on error /// public string? ReadString(string key) { if (!ValidateKey(key)) return null; string? asString = Read(key); if (asString is not null) return asString; string[]? asArray = Read(key); if (asArray is not null) #if NETFRAMEWORK || NETSTANDARD2_0 return string.Join(",", asArray); #else return string.Join(',', asArray); #endif // TODO: Add byte array conversion here // TODO: Add byte array read helper return this[key]!.ToString(); } /// /// Read a key as a string[], returning null on error /// public string[]? ReadStringArray(string key) { if (!ValidateKey(key)) return null; string[]? asArray = Read(key); if (asArray is not null) return asArray; string? asString = Read(key); if (asString is not null) return [asString]; asString = this[key]!.ToString(); if (asString is not null) return [asString]; return null; } /// /// Check if a key is valid /// private bool ValidateKey(string key) { if (string.IsNullOrEmpty(key)) return false; else if (!ContainsKey(key)) return false; else if (this[key] is null) return false; return true; } } }