using System.Text.Json;
using System.Text.Json.Serialization;

namespace RobotNet.WebApp.Charts.Enums;

public class LowerCaseEnumConverter<T> : JsonConverter<T> where T : struct, Enum
{
    public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetString();
        if (Enum.TryParse(value, true, out T result))
        {
            return result;
        }
        throw new JsonException($"Unable to convert \"{value}\" to enum {typeof(T)}.");
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString().ToLower());
    }
}

public class CamelCaseEnumConverter<T> : JsonConverter<T> where T : struct, Enum
{
    public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        string value = reader.GetString() ?? throw new JsonException();
        foreach (T enumValue in Enum.GetValues<T>())
        {
            if (string.Equals(CamelCaseEnumConverter<T>.ToCamelCase(enumValue.ToString()), value, StringComparison.OrdinalIgnoreCase))
            {
                return enumValue;
            }
        }
        throw new JsonException($"Unable to convert \"{value}\" to {typeof(T)}.");
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        string enumString = CamelCaseEnumConverter<T>.ToCamelCase(value.ToString());
        writer.WriteStringValue(enumString);
    }

    private static string ToCamelCase(string input)
    {
        if (string.IsNullOrEmpty(input) || char.IsLower(input[0]))
            return input;

        return char.ToLower(input[0]) + input[1..];
    }
}