using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace GameFix.Poker
{
    public class CardIdJsonConverter : JsonConverter
    {
        ICardIdResolver mResolver;
        public CardIdJsonConverter(ICardIdResolver resolver)
        {
            mResolver = resolver;
        }
        
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is IList<Card> cards)
            {
                writer.WriteStartArray();
                foreach (var card in cards)
                {
                    if (card != null)
                        writer.WriteValue(card.Id + 1);
                    else
                    {
                        writer.WriteValue(0);
                    }
                }
                writer.WriteEndArray();;
            } else if (value is Card card)
            {
                writer.WriteValue(card.Id + 1);
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            if (reader.TokenType == JsonToken.StartArray)
            {
                List<Card> cards = new List<Card>();
                while (reader.Read())
                {
                    if (reader.TokenType == JsonToken.EndArray)
                    {
                        break;
                    }
                    
                    if (reader.TokenType == JsonToken.Integer)
                    {
                        int id = Convert.ToInt32(reader.Value);     // 读取 ID 值
                        cards.Add(mResolver.GetById(id - 1));
                    }
                }

                return cards;
            }

            if (reader.TokenType == JsonToken.Integer)
            {
                int id = Convert.ToInt32(reader.Value);     // 读取 ID 值
                return mResolver.GetById(id - 1);
            }

            return null;
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(IList<Card>).IsAssignableFrom(objectType) || typeof(Card).IsAssignableFrom(objectType);
        }
    }
}