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

namespace adas_core.Domain.Models.BsonConverters;

public class DictionaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Dictionary<string, object>);
    }

    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;
    }

    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);
    }
}