// <copyright file="JsonDefaultStringEnumConverter.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

#pragma warning disable SA1309 // Variables should not begin with underscore

namespace Jellyfin.Extensions.Json.Converters
{
    using System;
    using System.ComponentModel;
    using System.Reflection;
    using System.Text.Json;
    using System.Text.Json.Serialization;

    /// <summary>
    /// Json unknown enum converter.
    /// </summary>
    /// <typeparam name="T">The type of enum.</typeparam>
    public class JsonDefaultStringEnumConverter<T> : JsonConverter<T>
        where T : struct, Enum
    {
        private readonly JsonConverter<T> _baseConverter;

        /// <summary>
        /// Initializes a new instance of the <see cref="JsonDefaultStringEnumConverter{T}"/> class.
        /// </summary>
        /// <param name="baseConverter">The base json converter.</param>
        public JsonDefaultStringEnumConverter(JsonConverter<T> baseConverter)
        {
            this._baseConverter = baseConverter;
        }

        /// <inheritdoc />
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            ArgumentNullException.ThrowIfNull(typeToConvert);
            if (reader.IsNull() || reader.IsEmptyString())
            {
                var customValueAttribute = typeToConvert.GetCustomAttribute<DefaultValueAttribute>();
                if (customValueAttribute?.Value is null)
                {
                    throw new InvalidOperationException($"Default value not set for '{typeToConvert.Name}'");
                }

                return (T)customValueAttribute.Value;
            }

            return this._baseConverter.Read(ref reader, typeToConvert, options);
        }

        /// <inheritdoc />
        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            this._baseConverter.Write(writer, value, options);
        }
    }
}
