using System.Text.Json;
using System.Text.Json.Serialization;
using Ethanol.MalwareSonar.Fuzzy;

public class FuzzySetJsonSerializer<T> : JsonConverter<FuzzySet<T>> where T : notnull
{
    public override FuzzySet<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.Null)
            return null;

        var values = JsonSerializer.Deserialize<KeyValuePair<T,double>[]>(ref reader, options);
        if (values != null)
        {
            return new FuzzySet<T>(new ValueBasedMembership<T>(values.ToDictionary(x => x.Key, x => x.Value)),
                values.Select(x => x.Key));
        }
        else
        {
            return null;
        }
    }

    public override void Write(Utf8JsonWriter writer, FuzzySet<T> value, JsonSerializerOptions options)
    {
        if (value == null)
        {
            writer.WriteNullValue();
            return;
        }
        var values = value.GetMembershipValues().ToArray();

        JsonSerializer.Serialize(writer, values, options);
    }
}

