using adas_core.Domain.Models.MongoModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace adas_core.Domain.Models.BsonConverters;

/// <summary>
/// Represents a JSON converter that handles serialization and deserialization of dictionary types.
/// </summary>
/// <remarks>
/// Inherits from <see cref="JsonConverter"/> to provide custom conversion logic for dictionary-shaped data.
/// </remarks>
public class DictionaryConverter : JsonConverter
{
    /// <summary>
    /// Determines whether the converter can handle the specified type.
    /// Returns <c>true</c> only when <paramref name="objectType"/> is exactly <see cref="Dictionary{TKey, TValue}"/> with string keys and object values.
    /// </summary>
    /// <param name="objectType">The type to evaluate for converter compatibility.</param>
    /// <returns><c>true</c> if the type is <see cref="Dictionary{TKey, TValue}"/> of string and object; otherwise, <c>false</c>.</returns>
    public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Dictionary<string, object>);
        }

    /// <summary>
    /// 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 <see cref="Step"/> and <see cref="LightBeacon"/> respectively, "cameras" as a list of <see cref="Camera"/>, "relay" as a <see cref="Relay"/> instance, and stores any other properties as generic objects, using empty collections or default instances when the source value is null.
    /// </summary>
    /// <param name="reader">The JSON reader used to read the input token.</param>
    /// <param name="objectType">The type of the object being deserialized.</param>
    /// <param name="existingValue">The existing value of the object being read.</param>
    /// <param name="serializer">The JSON serializer used to deserialize nested values.</param>
    /// <returns>A dictionary containing the JSON properties mapped to their deserialized values.</returns>
    public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
            JsonSerializer serializer)
        {
            var jo = JObject.Load(reader);
            Dictionary<string, object> stepsDictionary = new();
            foreach (var item in jo)
            {
                var key = item.Key;
    
                switch (item.Key)
                {
                    case "Steps":
                        var valueStep = item.Value?.ToObject<List<Step>>(serializer);
                        stepsDictionary.Add(key, valueStep ?? []);
                        break;
                    case "beacons":
                        var valueBeacon = item.Value?.ToObject<List<LightBeacon>>(serializer);
                        stepsDictionary.Add(key, valueBeacon ?? []);
                        break;
                    case "relay":
                        var valueRelay = item.Value?.ToObject<Relay>(serializer);
                        stepsDictionary.Add(key, valueRelay ?? new Relay());
                        break;
                    case "cameras":
                        var valueCameras = item.Value?.ToObject<List<Camera>>(serializer);
                        stepsDictionary.Add(key, valueCameras ?? []);
                        break;
                    default:
                        var valueDefault = item.Value?.ToObject<object>(serializer);
                        stepsDictionary.Add(key, valueDefault ?? new object());
                        break;
                }
            }
    
            return stepsDictionary;
        }

    /// <summary>
    /// Serializes a dictionary of entries to JSON, writing each key-value pair as a JSON property using the provided serializer. Returns immediately when the value is null, leaving the writer untouched.
    /// </summary>
    /// <param name="writer">The JSON writer that receives the serialized output.</param>
    /// <param name="value">The dictionary to serialize; if null, nothing is written.</param>
    /// <param name="serializer">The serializer used to convert each dictionary value into a JSON token.</param>
    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            if (value == null)
                return;
    
            var stepsDictionary = (Dictionary<string, object>)value;
            var jo = new JObject();
            foreach (var item in stepsDictionary) jo.Add(item.Key, JToken.FromObject(item.Value, serializer));
            jo.WriteTo(writer);
        }
}