using adas_core.Domain.Models.MongoModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace adas_core.Domain.Models.BsonConverters;
///
/// Represents a JSON converter that handles serialization and deserialization of dictionary types.
///
///
/// Inherits from to provide custom conversion logic for dictionary-shaped data.
///
public class DictionaryConverter : JsonConverter
{
///
/// Determines whether the converter can handle the specified type.
/// Returns true only when is exactly with string keys and object values.
///
/// The type to evaluate for converter compatibility.
/// true if the type is of string and object; otherwise, false.
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary);
}
///
/// Deserializes a JSON object into a dictionary where each key maps to a strongly-typed value based on the property name. Handles "Steps" and "beacons" as lists of and respectively, "cameras" as a list of , "relay" as a instance, and stores any other properties as generic objects, using empty collections or default instances when the source value is null.
///
/// The JSON reader used to read the input token.
/// The type of the object being deserialized.
/// The existing value of the object being read.
/// The JSON serializer used to deserialize nested values.
/// A dictionary containing the JSON properties mapped to their deserialized values.
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
JsonSerializer serializer)
{
var jo = JObject.Load(reader);
Dictionary stepsDictionary = new();
foreach (var item in jo)
{
var key = item.Key;
switch (item.Key)
{
case "Steps":
var valueStep = item.Value?.ToObject>(serializer);
stepsDictionary.Add(key, valueStep ?? []);
break;
case "beacons":
var valueBeacon = item.Value?.ToObject>(serializer);
stepsDictionary.Add(key, valueBeacon ?? []);
break;
case "relay":
var valueRelay = item.Value?.ToObject(serializer);
stepsDictionary.Add(key, valueRelay ?? new Relay());
break;
case "cameras":
var valueCameras = item.Value?.ToObject>(serializer);
stepsDictionary.Add(key, valueCameras ?? []);
break;
default:
var valueDefault = item.Value?.ToObject