using Newtonsoft.Json;

namespace Pilz.Net.Api;

public class DefaultApiMessageSerializer : IApiMessageSerializer
{
    private static JsonSerializerSettings? defaultSerializerSettings;

    public JsonSerializerSettings DefaultSerializerSettings => defaultSerializerSettings ??= CreateDefaultSerializerSettings();

    protected virtual JsonSerializerSettings CreateDefaultSerializerSettings()
    {
        return new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
        };
    }

    public virtual string? Serialize(ApiMessage message)
    {
        return JsonConvert.SerializeObject(message, DefaultSerializerSettings);
    }

    public virtual ApiMessage? Deserialize(string json, Type target)
    {
        return JsonConvert.DeserializeObject(json, target, DefaultSerializerSettings) as ApiMessage;
    }
}
