using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; namespace TimePasses.Model; [Serializable] public class WhenLevel : IWhen { public uint Level { get; init; } public int CompareResult { get; init; } public ReplacementText Text { get; init; } public bool Slowly { get; init; } public bool IsValid(Plugin plugin) { if (plugin.ClientState.LocalPlayer is not { } player) { return false; } var cmp = ((uint) player.Level).CompareTo(this.Level); return this.CompareResult switch { 1 when cmp > 0 => true, 0 when cmp == 0 => true, -1 when cmp < 0 => true, _ => false, }; } } public class WhenLevelConverter : IYamlTypeConverter { public bool Accepts(Type type) { return type == typeof(WhenLevel); } public object ReadYaml(IParser parser, Type type) { parser.Consume(); ReplacementText? text = null; int? comparerResult = null; uint? level = null; var slowly = false; while (parser.Current is not MappingEnd) { var key = parser.Consume(); if (!key.IsKey) { throw new YamlException("expected key"); } if (key.Value == "text") { text = (ReplacementText?) ReplacementTextConverter.Instance.ReadYaml(parser, type); continue; } var value = parser.Consume(); switch (key.Value) { case "greaterThan": { ParseOperation(1); break; } case "equalTo": { ParseOperation(0); break; } case "lessThan": { ParseOperation(-1); break; } case "slowly": { if (!bool.TryParse(value.Value, out slowly)) { throw new YamlException("invalid whenlevel: slowly was not a boolean"); } break; } default: { continue; } } continue; void ParseOperation(int comparer) { if (comparerResult != null) { throw new YamlException("duplicate operations in whenlevel"); } comparerResult = comparer; if (!uint.TryParse(value.Value, out var lvl)) { throw new YamlException("invalid whenlevel: level was not numeric"); } level = lvl; } } parser.Consume(); if (text == null) { throw new YamlException("invalid whenlevel: missing text"); } if (comparerResult == null) { throw new YamlException("invalid whenlevel: missing operation"); } if (level == null) { throw new YamlException("invalid whenlevel: missing level"); } return new WhenLevel { CompareResult = comparerResult.Value, Level = level.Value, Text = text, Slowly = slowly, }; } public void WriteYaml(IEmitter emitter, object? value, Type type) { throw new NotImplementedException(); } }