using System.Text.Json;
using System.Text.Json.Nodes;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers;
///
/// Shared millisecond helpers for the AB forms (#576): the driver factories bind *Ms integers
/// while the forms edit whole seconds, so a sub-second stored value must survive an edit of an
/// unrelated field.
///
internal static class DriverConfigMs
{
/// Reads an integer-millisecond key at from , or null.
public static int? Read(string? json, string path)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
JsonNode? cur = JsonNode.Parse(json);
foreach (var seg in path.Split('.'))
{
if (cur is not JsonObject o) return null;
cur = o.FirstOrDefault(kv => string.Equals(kv.Key, seg, StringComparison.OrdinalIgnoreCase)).Value;
}
return cur is JsonValue v && v.TryGetValue(out var ms) ? ms : null;
}
catch (JsonException) { return null; }
}
/// Whole seconds for display (truncating, like the pre-#576 forms).
public static int ToSeconds(TimeSpan t) => (int)t.TotalSeconds;
///
/// The duration to save: the loaded value when the operator left the seconds field unchanged
/// (keeps 500 ms from collapsing to 0 s), else the edited whole seconds.
///
public static TimeSpan Save(int seconds, TimeSpan? loaded)
=> loaded is { } l && ToSeconds(l) == seconds ? l : TimeSpan.FromSeconds(seconds);
}