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

namespace AsyncApiRenderer.Data;

public class JsonSchemaTypeConverter : JsonConverter<HashSet<JsonSchemaType>>
{
    public override HashSet<JsonSchemaType>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.StartArray)
        {
            var list = new HashSet<JsonSchemaType>();
            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                    case JsonTokenType.EndArray:
                        return list;
                    case JsonTokenType.String:
                        list.Add(Enum.Parse<JsonSchemaType>(reader.GetString()!, true));
                        break;
                    default:
                        throw new JsonException("Unsupported json type");
                }
            }
            throw new JsonException("No array end found");
        }
        if (reader.TokenType == JsonTokenType.String)
        {
            var value = reader.GetString()!;
            return new HashSet<JsonSchemaType>
            {
                Enum.Parse<JsonSchemaType>(value, true),
            };
        }
        throw new JsonException("Unexpected type");
    }

    public override void Write(Utf8JsonWriter writer, HashSet<JsonSchemaType> value, JsonSerializerOptions options)
    {
        if (value.Count == 1)
        {
            writer.WriteStringValue(value.First().ToString());
        }
        else
        {
            writer.WriteStartArray();
            foreach (var type in value)
                writer.WriteStringValue(type.ToString());
            writer.WriteEndArray();
        }
    }
}