using System;
using System.Collections.ObjectModel;
using System.Windows;

namespace PersonalToolBox.Helpers;

/// <summary>
/// 主题切换辅助类，动态替换 Application 的 ResourceDictionary
/// </summary>
public static class ThemeHelper
{
    private const string ThemePrefix = "Themes/";
    private const string DarkThemePath = "Themes/DarkTheme.xaml";
    private const string LightThemePath = "Themes/LightTheme.xaml";

    /// <summary>
    /// 切换主题（Dark / Light）
    /// </summary>
    public static void ApplyTheme(string theme)
    {
        var app = Application.Current;
        if (app == null) return;

        // 移除旧的主题资源字典
        var oldDict = FindThemeDictionary(app.Resources.MergedDictionaries);
        if (oldDict != null)
            app.Resources.MergedDictionaries.Remove(oldDict);

        // 加载新的主题资源字典
        var path = theme switch
        {
            "Light" => LightThemePath,
            _ => DarkThemePath
        };

        var newDict = new ResourceDictionary
        {
            Source = new Uri(path, UriKind.Relative)
        };
        app.Resources.MergedDictionaries.Add(newDict);
    }

    /// <summary>
    /// 在当前合并字典中查找主题相关的 ResourceDictionary
    /// </summary>
    private static ResourceDictionary? FindThemeDictionary(Collection<ResourceDictionary> dictionaries)
    {
        foreach (var dict in dictionaries)
        {
            if (dict.Source != null && dict.Source.OriginalString.StartsWith(ThemePrefix))
                return dict;
        }
        return null;
    }
}
