using System.Text.Json;
using System.Text.Json.Serialization;
using YandexMusic.API.Models.Landing.Entity.Entities;

namespace YandexMusic.API.Models.Landing.Entity;

/// <summary>Конвертер для сущностей лендинга (десериализация в конкретные типы на основе поля type).</summary>
public class YLandingEntityConverter : JsonConverter<List<YLandingEntity>>
{
    public override List<YLandingEntity> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartArray)
            throw new JsonException("Ожидается массив сущностей");

        var entities = new List<YLandingEntity>();
        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.EndArray)
                break;

            if (reader.TokenType != JsonTokenType.StartObject)
                throw new JsonException("Ожидается объект сущности");

            using var doc = JsonDocument.ParseValue(ref reader);
            var root = doc.RootElement;

            var typeProp = root.GetProperty("type");
            var typeStr = typeProp.GetString();
            if (!Enum.TryParse<YLandingEntityType>(typeStr, true, out var entityType))
                throw new JsonException($"Неизвестный тип сущности: {typeStr}");

            YLandingEntity? entity = null;
            var rawText = root.GetRawText();

            switch (entityType)
            {
                case YLandingEntityType.Album:
                    entity = JsonSerializer.Deserialize<YLandingEntityAlbum>(rawText, options);
                    break;
                case YLandingEntityType.ChartItem:
                    entity = JsonSerializer.Deserialize<YLandingEntityChart>(rawText, options);
                    break;
                case YLandingEntityType.PersonalPlaylist:
                    entity = JsonSerializer.Deserialize<YLandingEntityPersonalPlaylist>(rawText, options);
                    break;
                case YLandingEntityType.PlayContext:
                    entity = JsonSerializer.Deserialize<YLandingEntityPlayContext>(rawText, options);
                    break;
                case YLandingEntityType.Playlist:
                    entity = JsonSerializer.Deserialize<YLandingEntityPlaylist>(rawText, options);
                    break;
                case YLandingEntityType.Podcast:
                    entity = JsonSerializer.Deserialize<YLandingEntityPodcast>(rawText, options);
                    break;
                case YLandingEntityType.Promotion:
                    entity = JsonSerializer.Deserialize<YLandingEntityPromotion>(rawText, options);
                    break;
                case YLandingEntityType.Category:
                    entity = JsonSerializer.Deserialize<YLandingEntityCategory>(rawText, options);
                    break;
                case YLandingEntityType.Station:
                    entity = JsonSerializer.Deserialize<YLandingEntityStation>(rawText, options);
                    break;
                case YLandingEntityType.MenuItemAlbum:
                case YLandingEntityType.MenuItemPlaylist:
                    entity = JsonSerializer.Deserialize<YLandingEntityAlbumMenuItem>(rawText, options);
                    break;
                case YLandingEntityType.ClientWidget:
                    entity = JsonSerializer.Deserialize<YLandingEntityClientWidget>(rawText, options);
                    break;
                default:
                    entity = JsonSerializer.Deserialize<YLandingEntity>(rawText, options);
                    break;
            }

            if (entity != null)
                entities.Add(entity);
        }
        return entities;
    }

    public override void Write(Utf8JsonWriter writer, List<YLandingEntity> value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, value, options);
    }
}
