using adas_core.Domain.Models.MongoModels;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using Newtonsoft.Json.Linq;
namespace adas_core.Domain.Models.BsonConverters;
///
/// A BSON converter responsible for serializing and deserializing
/// instances with string keys and object values,
/// extending the base serializer infrastructure to support BSON format conversion.
///
///
/// This type specializes the generic base serializer for the specific dictionary shape
/// Dictionary<string, object>, providing a focused implementation for
/// BSON-based persistence and data interchange scenarios.
///
public class DictionaryBsonConverter : SerializerBase>
{
///
/// Deserializes a BSON document into a dictionary where each top-level field name is mapped to its corresponding value.
/// Recognized keys (STEPS, BEACONS, CAMERAS, RELAY) are deserialized into their strongly-typed collections or objects, while unknown keys are deserialized based on the current BSON type (numeric values, strings, booleans, arrays of mixed primitive types, or generic BSON documents).
/// If the current BSON value is not a document, an empty dictionary is returned.
///
/// The BSON deserialization context providing the reader used to traverse the BSON payload.
/// The BSON deserialization arguments carrying additional configuration for the deserialization process.
/// A dictionary containing the deserialized key/value pairs extracted from the BSON document.
public override Dictionary Deserialize(BsonDeserializationContext context,
BsonDeserializationArgs args)
{
var reader = context.Reader;
var stepsDictionary = new Dictionary();
if (reader.CurrentBsonType == BsonType.Document)
{
reader.ReadStartDocument();
while (reader.ReadBsonType() != BsonType.EndOfDocument)
{
var key = reader.ReadName();
switch (key.ToUpper())
{
case "STEPS":
var stepList = BsonSerializer.Deserialize>(reader);
stepsDictionary[key] = stepList;
break;
case "BEACONS":
var beaconList = BsonSerializer.Deserialize>(reader);
stepsDictionary[key] = beaconList;
break;
case "CAMERAS":
var cameraList = BsonSerializer.Deserialize>(reader);
stepsDictionary[key] = cameraList;
break;
case "RELAY":
var relayList = BsonSerializer.Deserialize(reader);
stepsDictionary[key] = relayList;
break;
default:
switch (reader.CurrentBsonType)
{
case BsonType.Int32:
case BsonType.Int64:
stepsDictionary[key] = BsonSerializer.Deserialize(reader);
break;
case BsonType.Double:
stepsDictionary[key] = BsonSerializer.Deserialize(reader);
break;
case BsonType.String:
stepsDictionary[key] = BsonSerializer.Deserialize(reader);
break;
case BsonType.Boolean:
stepsDictionary[key] = BsonSerializer.Deserialize(reader);
break;
case BsonType.Array:
reader.ReadStartArray();
var arrayItems = new List