using System.Reflection; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using ArcaneLibs.Extensions; namespace LibMatrix.EventTypes; // : MatrixEventContent where T : MatrixEventContent, new() { /// /// Extensible Event Content, aims to provide an API similar to JsonNode/JsonObject /// /// /// [JsonConverter(typeof(MatrixEventContentConverter))] // [JsonSerializable(typeof(MatrixEventContent))] public class BaseMatrixEventContent { public JsonObject InternalJson { get; set; } = new(); public BaseMatrixEventContent() { } public BaseMatrixEventContent(JsonNode json) { InternalJson = json.AsObject(); } public static implicit operator BaseMatrixEventContent(JsonNode json) => new(json); // public static implicit operator JsonNode(MatrixEventContent content) => content.InternalJson; [JsonIgnore] public IEnumerable EventTypes => this.GetType().GetCustomAttributes().Select(x => x.EventType); [JsonIgnore] public string EventType => EventTypes.First(); public JsonNode? this[string key] => InternalJson[key]; public string ToJson() => InternalJson.ToJson(); public class MatrixEventContentConverter : JsonConverter where T : BaseMatrixEventContent, new() { public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // read entire object into a JsonObject // Console.WriteLine($"MatrixEventContentConverter: Reading {typeToConvert}"); var json = JsonNode.Parse(ref reader); return new T { InternalJson = json.AsObject() }; } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { // Console.WriteLine($"MatrixEventContentConverter: Writing {value.GetType()}"); value.InternalJson.WriteTo(writer); } } }