#if !UNITY_WEBGL
using Newtonsoft.Json;
using System;

namespace Combo.Core
{
    public class EmptyStringToBoolConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue((bool)value);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                var stringValue = reader.Value as string;
                if (string.IsNullOrEmpty(stringValue))
                {
                    // 默认返回 false
                    return false;
                }
                if (bool.TryParse(stringValue, out bool result))
                {
                    return result;
                }
            }
            else if (reader.TokenType == JsonToken.Boolean)
            {
                return reader.Value;
            }

            throw new JsonSerializationException("Unexpected token type for boolean value.");
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(bool);
        }
    }
}
#endif