using System.Globalization;
using System.Windows.Data;

namespace DragonISO.App.Converters;

/// <summary>
/// Maps an audio level (0.0â€“1.0) to an opacity for a single audio-meter
/// segment. The XAML binds five copies, each with a different
/// <see cref="Binding.ConverterParameter"/> threshold (0.2, 0.4, 0.6,
/// 0.8, 1.0). A segment renders at full opacity when the live level
/// exceeds its threshold; below that it dims to a faint silhouette so the
/// inactive segments still read as "the meter has 5 steps" rather than
/// blank space.
///
/// Designed for the v2 "Studio Terminal" participants table's audio meter.
/// Broadcast engineers expect instantaneous (non-averaged) bars; the
/// converter is stateless and trusts the caller to push raw levels.
/// </summary>
public sealed class LevelThresholdConverter : IValueConverter
{
    /// <summary>Opacity for an above-threshold segment. Defaults to 1.0.</summary>
    public double ActiveOpacity { get; set; } = 1.0;

    /// <summary>Opacity for a below-threshold segment. Defaults to 0.18 â€” visible enough to read the segment shape but clearly off.</summary>
    public double InactiveOpacity { get; set; } = 0.18;

    public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture)
    {
        var level = value switch
        {
            double d => d,
            float f => f,
            _ => 0.0,
        };
        if (!double.TryParse(parameter?.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var threshold))
            threshold = 1.0;
        return level >= threshold ? ActiveOpacity : InactiveOpacity;
    }

    public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) =>
        System.Windows.Data.Binding.DoNothing;
}
