using System.Text.Json;
using System.Text.Json.Serialization;

namespace FrameProcessor.Domain;

[JsonConverter(typeof(DitherAlgorithmJsonConverter))]
public enum DitherAlgorithm
{
    FloydSteinberg,
    Atkinson,
    Stucki,
    Jarvis,
}

internal sealed class DitherAlgorithmJsonConverter : JsonConverter<DitherAlgorithm>
{
    public override DitherAlgorithm Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var s = reader.GetString();
        return s switch
        {
            "floyd-steinberg" => DitherAlgorithm.FloydSteinberg,
            "atkinson" => DitherAlgorithm.Atkinson,
            "stucki" => DitherAlgorithm.Stucki,
            "jarvis" => DitherAlgorithm.Jarvis,
            _ => throw new JsonException(
                $"'{s}' is not a valid dither algorithm. Expected 'floyd-steinberg', 'atkinson', 'stucki', or 'jarvis'."),
        };
    }

    public override void Write(Utf8JsonWriter writer, DitherAlgorithm value, JsonSerializerOptions options)
        => writer.WriteStringValue(value switch
        {
            DitherAlgorithm.FloydSteinberg => "floyd-steinberg",
            DitherAlgorithm.Atkinson => "atkinson",
            DitherAlgorithm.Stucki => "stucki",
            DitherAlgorithm.Jarvis => "jarvis",
            _ => throw new JsonException($"Unknown dither algorithm: {value}."),
        });
}
