using System; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; namespace Syntriax.Engine.Core.Serialization; public class BehaviourSerializer : IEngineTypeYamlSerializer { private const string SERIALIZED_SCALAR_NAME = "Properties"; public bool Accepts(Type type) => typeof(IBehaviour).IsAssignableFrom(type); public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string id; int priority; IBehaviour behaviour; IStateEnable stateEnable; parser.Consume(); if (parser.Consume().Value.CompareTo(nameof(IBehaviour.Id)) != 0) throw new(); id = parser.Consume().Value; if (parser.Consume().Value.CompareTo(nameof(IBehaviour.Priority)) != 0) throw new(); priority = int.Parse(parser.Consume().Value); if (parser.Consume().Value.CompareTo(SERIALIZED_SCALAR_NAME) != 0) throw new(); SerializedClass instanceSerializedClass = (SerializedClass)rootDeserializer(typeof(SerializedClass))!; behaviour = (IBehaviour)instanceSerializedClass.CreateInstance(); if (parser.Consume().Value.CompareTo(nameof(IBehaviour.StateEnable)) != 0) throw new(); stateEnable = (IStateEnable)rootDeserializer(typeof(IStateEnable))!; parser.Consume(); behaviour.Id = id; behaviour.Priority = priority; stateEnable.Assign(behaviour); behaviour.Assign(stateEnable); return behaviour; } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { IBehaviour behaviour = (IBehaviour)value!; emitter.Emit(new MappingStart()); emitter.Emit(new Scalar(nameof(IBehaviour.Id))); emitter.Emit(new Scalar(behaviour.Id)); emitter.Emit(new Scalar(nameof(IBehaviour.Priority))); emitter.Emit(new Scalar(behaviour.Priority.ToString())); emitter.Emit(new Scalar(SERIALIZED_SCALAR_NAME)); serializer(new SerializedClass(behaviour)); emitter.Emit(new Scalar(nameof(IBehaviour.StateEnable))); serializer(behaviour.StateEnable); emitter.Emit(new MappingEnd()); } }