using System.Text.Json;
using System.Text.Json.Serialization;
using ColorHelper;
namespace Terminal.Gui;
///
/// Json converter for the class.
///
/// Serialization outputs a string with the color name if the color matches a name in
/// or the "#RRGGBB" hexadecimal representation (e.g. "#FF0000" for red).
///
///
/// Deserialization formats supported are "#RGB", "#RRGGBB", "#ARGB", "#AARRGGBB", "rgb(r,g,b)",
/// "rgb(r,g,b,a)", "rgba(r,g,b)", "rgba(r,g,b,a)", or any W3C color name.
///
internal class ColorJsonConverter : JsonConverter
{
private static ColorJsonConverter _instance;
/// Singleton
public static ColorJsonConverter Instance
{
get
{
if (_instance is null)
{
_instance = new ();
}
return _instance;
}
}
public override Color Read (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Check if the value is a string
if (reader.TokenType == JsonTokenType.String)
{
// Get the color string
ReadOnlySpan colorString = reader.GetString ();
// Check if the color string is a color name
if (ColorStrings.TryParseW3CColorName (colorString.ToString (), out Color color1))
{
// Return the parsed color
return new (color1);
}
if (Color.TryParse (colorString, null, out Color parsedColor))
{
return parsedColor;
}
throw new JsonException ($"Unexpected color name: {colorString}.");
}
throw new JsonException ($"Unexpected token when parsing Color: {reader.TokenType}");
}
public override void Write (Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
{
writer.WriteStringValue (value.ToString ());
}
}