using Newtonsoft.Json;
using Pilz.Cryptography;
using System;
using System.Collections.Generic;
using System.Text;

namespace Pilz.Json.Converters
{
    public class UniquieIDStringJsonConverter : JsonConverter
    {
        public static bool EnableCheckForDepricatedTypes { get; set; } = true;

        public override bool CanConvert(Type objectType)
        {
            return typeof(IUniquieID).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var idString = serializer.Deserialize<string>(reader);
            UniquieID id;

            if (existingValue is UniquieID existingID && (!EnableCheckForDepricatedTypes || existingID.GetType() == typeof(UniquieID)))
                id = existingID;
            else
                id = new UniquieID();

            id.ID = idString;

            return id;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, ((UniquieID)value).ID);
        }
    }
}
