using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace SharepointToolbox.Views.Converters;

/// <summary>
/// Converts a data URI string (e.g. "data:image/png;base64,iVBOR...") to a BitmapImage
/// for use with WPF Image controls. Returns null for null, empty, or malformed input.
/// </summary>
[ValueConversion(typeof(string), typeof(BitmapImage))]
public class Base64ToImageSourceConverter : IValueConverter
{
    public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is not string dataUri || string.IsNullOrEmpty(dataUri))
            return null;

        try
        {
            var marker = "base64,";
            var idx = dataUri.IndexOf(marker, StringComparison.Ordinal);
            if (idx < 0) return null;

            var base64 = dataUri[(idx + marker.Length)..];
            var bytes = System.Convert.FromBase64String(base64);

            var image = new BitmapImage();
            using var ms = new MemoryStream(bytes);
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.StreamSource = ms;
            image.EndInit();
            image.Freeze();
            return image;
        }
        catch
        {
            return null;
        }
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
        => throw new NotImplementedException();
}
