using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using WinRT.Interop;

namespace YMhut.Box.WinUI.Services;

public static class WindowIconService
{
    public static void ApplyAppIcon(Window? window)
    {
        if (window is null)
        {
            return;
        }

        try
        {
            var iconPath = ResolveIconPath();
            if (iconPath is null)
            {
                return;
            }

            var hwnd = WindowNative.GetWindowHandle(window);
            var id = Win32Interop.GetWindowIdFromWindow(hwnd);
            AppWindow.GetFromWindowId(id).SetIcon(iconPath);
        }
        catch (Exception exception)
        {
            CrashLog.Write(exception);
        }
    }

    public static string? ResolveIconPath()
    {
        foreach (var path in new[]
        {
            Path.Combine(AppContext.BaseDirectory, "Assets", "app_icon.ico"),
            Path.Combine(AppContext.BaseDirectory, "Assets", "icons", "app_icon.ico"),
            Path.Combine(AppContext.BaseDirectory, "app_icon.ico")
        })
        {
            if (File.Exists(path))
            {
                return path;
            }
        }

        return null;
    }
}
