using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Imaging;
using System;

namespace Sonex.Client.Controls;

public class NavigationViewImageItem : NavigationViewItem
{
    public string? IconPath
    {
        get => (string?)GetValue(IconPathProperty);
        set => SetValue(IconPathProperty, value);
    }

    public static readonly DependencyProperty IconPathProperty =
        DependencyProperty.Register(
            nameof(IconPath),
            typeof(string),
            typeof(NavigationViewImageItem),
            new PropertyMetadata(null, OnIconChanged));

    private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not NavigationViewImageItem item || string.IsNullOrWhiteSpace(item.IconPath))
            return;

        string path = item.IconPath!;

        if (path.EndsWith(".svg", StringComparison.OrdinalIgnoreCase))
        {
            item.Icon = new ImageIcon
            {
                Source = new SvgImageSource(new Uri($"ms-appx:///{path}"))
            };
        }
        else
        {
            item.Icon = new BitmapIcon
            {
                UriSource = new Uri($"ms-appx:///{path}"),
                ShowAsMonochrome = false
            };
        }
    }
}