using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace LSFE.Infrastructure.Converter
{
    public class GuidListConverter : JsonConverter<List<Guid>>
    {
        public override List<Guid> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var list = new List<Guid>();

            if (reader.TokenType != JsonTokenType.StartArray)
                throw new JsonException();

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndArray)
                    return list;

                if (reader.TokenType == JsonTokenType.String)
                {
                    var str = reader.GetString();
                    if (Guid.TryParse(str, out var guid))
                        list.Add(guid);
                }
                else if (reader.TokenType == JsonTokenType.PropertyName)
                {
                }
            }

            return list;
        }

        public override void Write(Utf8JsonWriter writer, List<Guid> value, JsonSerializerOptions options)
        {
            writer.WriteStartArray();
            foreach (var guid in value)
                writer.WriteStringValue(guid.ToString());
            writer.WriteEndArray();
        }
    }
}
