using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Atomx.Utils.Json.Converts
{
	public class ClaimConverter : JsonConverter<Claim>
	{
		public override bool CanConvert(Type typeToConvert)
		{
			return typeToConvert == typeof(Claim);
		}

		public override Claim Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			using (var jsonDocument = JsonDocument.ParseValue(ref reader))
			{
				var text = jsonDocument.RootElement.GetRawText();
				var data = JsonSerializer.Deserialize<ClaimLite>(text, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
				return new Claim(data?.Type ?? string.Empty, data?.Value ?? string.Empty, data?.ValueType ?? string.Empty);
			}
		}

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

	public class ClaimLite
	{
		public string Type { get; set; } = string.Empty;
		public string Value { get; set; } = string.Empty;
		public string ValueType { get; set; } = string.Empty;
	}
}
