GPAL - Generally Positive Automation Library v1.0
GPAL The Fluent Automation LIbrary
Loading...
Searching...
No Matches
WaitTimeYamlConverter.cs
1// =============================================================================
2// GPAL - Generally Positive Automation Library
3// Copyright © 2026 Software Decisions, Inc. All rights reserved.
4//
5// This file is part of GPAL.
6// Licensed under the Business Source License 1.1
7//
8// Primary development, architecture, and vision by Michael B. Vederman,
9// CEO of Software Decisions, Inc., Texas.
10//
11// Internal development maintained privately.
12// Public releases appear on GitHub: https://github.com/SoftwareDecisionsInc/GPAL.
13//
14// See LICENSE for full terms, including Additional Use Grant.
15// =============================================================================
16
17using System;
18using System.Collections.Generic;
19using System.Linq;
20using YamlDotNet.Core;
21using YamlDotNet.Core.Events;
22using YamlDotNet.Serialization;
23using YamlDotNet.Serialization.TypeInspectors;
24using static GenerallyPositive.Enums;
25
26public sealed class WaitTimeYamlConverter : IYamlTypeConverter
27{
28 public bool Accepts(Type type) => type == typeof(WaitTime);
29
30 public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
31 {
32 // Handle scalar form: "Forever", "500", "Immediate", etc.
33 if (parser.Current is Scalar scalar)
34 {
35 parser.MoveNext(); // consume the scalar
36
37 if (WaitTime.TryFromString(scalar.Value, out var result))
38 {
39 return result;
40 }
41
42 throw new YamlException(scalar.Start, scalar.End,
43 $"Unable to parse WaitTime from scalar value '{scalar.Value}'.");
44 }
45
46 // Handle mapping form: { Forever: null }, { 1000: null }, {}, etc.
47 if (parser.Current is MappingStart)
48 {
49 parser.MoveNext(); // consume MappingStart
50
51 // Deserialize the mapping as a dictionary
52 var dictionary = (IDictionary<object, object>)rootDeserializer(typeof(Dictionary<object, object>));
53
54 // Expect and consume MappingEnd
55 if (!(parser.Current is MappingEnd))
56 {
57 throw new YamlException("Expected MappingEnd after WaitTime mapping.");
58 }
59 parser.MoveNext(); // consume MappingEnd
60
61 if (WaitTime.TryFromDictionary(dictionary, out var result))
62 {
63 return result;
64 }
65
66 throw new YamlException("Invalid mapping format for WaitTime.");
67 }
68
69 // Fallback (null or unexpected) > Immediate
70 parser.MoveNext();
71 return WaitTime.Immediate;
72 }
73
74 public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer)
75 {
76 var waitTime = value is WaitTime wt ? wt : WaitTime.Immediate;
77
78 // Emit clean scalar: Forever, Never, Immediate, or the number
79 string text = waitTime.ToString();
80
81 emitter.Emit(new Scalar(text));
82 }
83}