TimePasses/Model/WhenLevel.cs

119 lines
3.3 KiB
C#
Raw Normal View History

2024-06-17 19:04:13 +00:00
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 string Text { get; init; }
public bool Slowly { get; init; }
public bool IsValid(Plugin plugin) {
if (plugin.ClientState.LocalPlayer is not { } player) {
return false;
}
2024-06-17 19:07:30 +00:00
var cmp = ((uint) player.Level).CompareTo(this.Level);
2024-06-17 19:04:13 +00:00
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<MappingStart>();
string? text = null;
int? comparerResult = null;
uint? level = null;
var slowly = false;
while (parser.Current is not MappingEnd) {
var key = parser.Consume<Scalar>();
if (!key.IsKey) {
throw new YamlException("expected key");
}
var value = parser.Consume<Scalar>();
2024-06-17 19:07:30 +00:00
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;
}
2024-06-17 19:04:13 +00:00
switch (key.Value) {
case "greaterThan": {
2024-06-17 19:07:30 +00:00
ParseOperation(1);
2024-06-17 19:04:13 +00:00
break;
}
case "equalTo": {
2024-06-17 19:07:30 +00:00
ParseOperation(0);
2024-06-17 19:04:13 +00:00
break;
}
case "lessThan": {
2024-06-17 19:07:30 +00:00
ParseOperation(-1);
2024-06-17 19:04:13 +00:00
break;
}
case "text": {
text = value.Value;
break;
}
case "slowly": {
if (!bool.TryParse(value.Value, out slowly)) {
throw new YamlException("invalid whenlevel: slowly was not a boolean");
}
break;
}
default: {
continue;
}
}
}
parser.Consume<MappingEnd>();
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,
};
}
2024-06-17 19:07:30 +00:00
public void WriteYaml(IEmitter emitter, object? value, Type type) {
2024-06-17 19:04:13 +00:00
throw new NotImplementedException();
}
}