using System.Text.Json;
using System.Text.Json.Serialization;
using YandexMusic.API.Models.Common;

namespace YandexMusic.API.Models.Album;

/// <summary>Конвертер для поля Labels, которое может быть списком строк или объектов.</summary>
public sealed class YLabelConverter : JsonConverter<object>
{
    public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartArray)
            throw new JsonException("Ожидается массив");

        var list = new List<object>();
        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.EndArray) break;
            if (reader.TokenType == JsonTokenType.String)
                list.Add(reader.GetString()!);
            else if (reader.TokenType == JsonTokenType.StartObject)
            {
                var label = JsonSerializer.Deserialize<YLabel>(ref reader, options);
                list.Add(label!);
            }
        }
        return list;
    }

    public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
        => JsonSerializer.Serialize(writer, value, options);
}
