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

namespace MangaReader.Core.Sources.MangaDex.Api;

public class MangaDexResponseConverter : JsonConverter<MangaDexResponse>
{
    public override MangaDexResponse? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using JsonDocument doc = JsonDocument.ParseValue(ref reader);
        JsonElement root = doc.RootElement;

        string result = root.GetProperty("result").GetString() ?? "fail";
        string response = root.GetProperty("response").GetString() ?? "unknown";

        JsonElement dataProperty = root.GetProperty("data");

        if (response == "collection" && dataProperty.ValueKind == JsonValueKind.Array)
        {
            MangaDexCollectionResponse collectionResponse = new()
            {
                Result = result,
                Response = response,
                Data = []
            };

            foreach (var item in dataProperty.EnumerateArray())
            {
                MangaDexEntity? entity = JsonSerializer.Deserialize<MangaDexEntity>(item.GetRawText(), options);

                if (entity != null)
                    collectionResponse.Data.Add(entity);
            }

            return collectionResponse;
        }
        else if (response == "entity" && dataProperty.ValueKind == JsonValueKind.Object)
        {
            MangaDexEntityResponse entityResponse = new()
            {
                Result = result,
                Response = response,
                Data = JsonSerializer.Deserialize<MangaDexEntity>(dataProperty.GetRawText(), options)
            };

            return entityResponse;
        }
        else
        {
            return new()
            {
                Result = result,
                Response = response
            };
        }
    }

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