Syntriax.Engine/Engine.Serialization/BehaviourControllerYamlConv...

54 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using Engine.Serialization.DTOs;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Engine.Serialization;
internal class BehaviourControllerYamlConverter : IYamlTypeConverter
{
public bool Accepts(Type type) => type == typeof(BehaviourControllerDTO);
public object ReadYaml(IParser parser, Type type)
{
if (parser.Current is not MappingStart)
throw new InvalidOperationException("Expected MappingStart");
parser.MoveNext();
var behaviourController = new BehaviourControllerDTO();
while (parser.Current != null && parser.Current is not MappingEnd)
{
var propertyName = ((Scalar)parser.Current).Value;
parser.MoveNext();
switch (propertyName)
{
case nameof(BehaviourControllerDTO.ClassType):
behaviourController.ClassType = ((Scalar)parser.Current).Value;
break;
case nameof(BehaviourControllerDTO.Behaviours):
behaviourController.Behaviours = (List<BehaviourDTO>)new BehaviourDTOListConverter().ReadYaml(parser, typeof(List<BehaviourDTO>));
break;
}
parser.MoveNext();
}
return behaviourController;
}
public void WriteYaml(IEmitter emitter, object? value, Type type)
{
var behaviourController = (BehaviourControllerDTO)(value ?? throw new Exception());
BehaviourDTOListConverter behaviourDTOListConverter = new();
emitter.Emit(new MappingStart());
emitter.Emit(new Scalar(nameof(BehaviourControllerDTO.ClassType)));
emitter.Emit(new Scalar(behaviourController.ClassType));
emitter.Emit(new Scalar(nameof(BehaviourControllerDTO.Behaviours)));
behaviourDTOListConverter.WriteYaml(emitter, behaviourController.Behaviours, typeof(List<BehaviourDTO>));
emitter.Emit(new MappingEnd());
}
}